How do I make a python script executable?

2019-01-21 20:19发布

How can I run a python script with my own command line name like 'myscript' without having to do 'python myscript.py' in the terminal?

3条回答
何必那么认真
2楼-- · 2019-01-21 20:58

I usually do in the script:

#!/usr/bin/python
... code ...

And in terminal:

$: chmod 755 yourfile.py
$: ./yourfile.py

permission table

查看更多
老娘就宠你
3楼-- · 2019-01-21 21:16
  1. Add a shebang line to the top of the script:

    #!/usr/bin/env python

  2. Mark the script as executable:

    chmod +x myscript.py

  3. Add the dir containing it to your PATH variable. (If you want it to stick, you'll have to do this in .bashrc or .bash_profile in your home dir.)

    export PATH=/path/to/script:$PATH

查看更多
Explosion°爆炸
4楼-- · 2019-01-21 21:16

The best way, which is cross-platform, is to create setup.py, define an entry point in it and install with pip.

Say you have the following contents of myscript.py:

def run():
    print('Hello world')

Then you add setup.py with the following:

from setuptools import setup
setup(
    name='myscript',
    version='0.0.1',
    entry_points={
        'console_scripts': [
            'myscript=myscript:run'
        ]
    }
)

Entry point format is terminal_command_name=python_script_name:main_method_name

Finally install with the following command.

pip install -e /path/to/script/folder

-e stands for editable, meaning you'll be able to work on the script and invoke the latest version without need to reinstall

After that you can run myscript from any directory.

查看更多
登录 后发表回答