liaa
V2EX  ›  问与答

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

  •  
  •   liaa · Jun 21, 2014 · 3625 views
    This topic created in 4415 days ago, the information mentioned may be changed or developed.
    用python写一个命令行脚本greet.py比如打印出"hello world".每次使用的时候都需要在终端敲下这个

    > python greet.py
    > "hello world"

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

    > greet
    > "hello world"

    * 不需要输入python
    * 不要定位到greet.py所在的文件夹中去执行
    Supplement 1  ·  Jun 21, 2014
    @Cynic222 纠正你一下,需要加上引号

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

    @binux 添加#! /usr/bin/env python.然后直接拷过去改名未成功...mac下面操作的
    Supplement 2  ·  Jun 22, 2014
    有同样问题的人请看这个stackoverflow 问题. 我已经用上了:

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

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

    然后将这个文件拷贝或者软连接到 /usr/local/bin/ 下,改名为 greet
    tongle
        4
    tongle  
       Jun 21, 2014
    在/user/bin下做个链接到greet.py就可以了
    tongle
        5
    tongle  
       Jun 21, 2014   ❤️ 1
    @tongle 手滑了,见笑
    timonwong
        6
    timonwong  
       Jun 22, 2014   ❤️ 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  
       Jun 22, 2014 via Android
    #添加 #!/usr/bin/env python 到文件开头
    sudo cp greet.py /usr/bin/greet
    sudo chmod +x /usr/bin/greet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1027 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 18:51 · PVG 02:51 · LAX 11:51 · JFK 14:51
    ♥ Do have faith in what you're doing.