V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
liaa
V2EX  ›  问与答

求教 python 命令行工具编写问题

  •  
  •   liaa · 2014-06-21 22:46:18 +08:00 · 2827 次点击
    这是一个创建于 3598 天前的主题,其中的信息可能已经有所发展或是发生改变。
    用python写一个命令行脚本greet.py比如打印出"hello world".每次使用的时候都需要在终端敲下这个

    > python greet.py
    > "hello world"

    请问如何将这个greet.py转变成下面这种直接调用的方式

    > greet
    > "hello world"

    * 不需要输入python
    * 不要定位到greet.py所在的文件夹中去执行
    第 1 条附言  ·  2014-06-21 23:25:06 +08:00
    @Cynic222 纠正你一下,需要加上引号

    alias greet='python /yout_path/greet.py'

    @binux 添加#! /usr/bin/env python.然后直接拷过去改名未成功...mac下面操作的
    第 2 条附言  ·  2014-06-22 00:45:39 +08:00
    有同样问题的人请看这个stackoverflow 问题. 我已经用上了:

    http://stackoverflow.com/questions/24343287/how-could-i-share-my-python-command-line-tool-to-the-wild
    7 条回复    2014-06-22 09:27:43 +08:00
    Cynic222
        1
    Cynic222  
       2014-06-21 22:49:12 +08:00   ❤️ 2
    alias greet=python /yout_path/greet.py
    liaa
        2
    liaa  
    OP
       2014-06-21 22:53:35 +08:00
    @Cynic222 嗯,这对我来说够用了!

    我希望把这个脚本打包给其他人用,但是不需要他们手动去做alias,应该怎么做才最好.
    binux
        3
    binux  
       2014-06-21 22:54:31 +08:00   ❤️ 1
    #!/usr/bin/env python

    然后将这个文件拷贝或者软连接到 /usr/local/bin/ 下,改名为 greet
    tongle
        4
    tongle  
       2014-06-21 22:57:48 +08:00
    在/user/bin下做个链接到greet.py就可以了
    tongle
        5
    tongle  
       2014-06-21 23:03:16 +08:00   ❤️ 1
    @tongle 手滑了,见笑
    timonwong
        6
    timonwong  
       2014-06-22 00:17:58 +08:00   ❤️ 1
    The Hard Way (and cross platform, on windows, it will generated a launcher application named greet.exe):

    # Requirements

    * setuptools
    * Define your main function, for example: def main()

    setup.py:


    from setuptools import setup

    setup(
    # other arguments here...
    py_modules=['greet.py'],
    entry_points={
    'console_scripts': [
    'greet = greet:main',
    ],
    }
    )
    lm902
        7
    lm902  
       2014-06-22 09:27:43 +08:00 via Android
    #添加 #!/usr/bin/env python 到文件开头
    sudo cp greet.py /usr/bin/greet
    sudo chmod +x /usr/bin/greet
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   907 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:08 · PVG 06:08 · LAX 15:08 · JFK 18:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.