简体   繁体   中英

running a python script in the command line from any directory

apologies in advance for a naive question. i've been doing some digging on here and still feel a bit confused.

i have a python script that i'd like to make executable from anywhere in a bash shell (like how git , homebrew , neofetch , etc. can all be called). i've used pyinstall to make an executable, but i don't quite know what to do with this. i tried moving the build folder to usr/local and putting an alias for the executable in usr/local/bin , but i got a 'cannot execute binary file' error when trying to run from the shell. i tried this after referencing the 'git' alias in urs/local/bin , and seeing that it directed to an executable in the usr/local .

does anyone know of any suggestions, or know of any good resources to try and understand what i'm doing wrong? thanks much!

For a simple script, the easiest way to make it executable is to simply add a Python shebang line , save the script to a directory that's on your PATH (eg /usr/local/bin ) and set the executable bit on the script.

Eg

#!/usr/bin/python3
import sys
print('Hello, world! I am Python', sys.version)

saved as /usr/local/bin/python-hello followed by chmod u+x /usr/local/bin/python-hello will let you execute python-hello from anywhere.

More complex scripts are best made executable by packaging them correctly with a properconsole_scripts entry point -- though something packed with PyInstaller would also work, although it'd be much heavier.

EDIT

A script with multiple modules should be organized into a package, eg

python_hello/
  __init__.py
  __main__.py
  greetings.py

__main__.py could then look like

def main():
    # ...

if __name__ == "__main__":
    main()

This way you can run the script with python -m python_hello as well as set up python_hello.__main__:main as a console script entry point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM