How to make an executable to use in a shell - Pyth

2019-08-05 05:13发布

I have a Python script and I was wondering how I can make it executable; in other words how can I run it by using a shell like bash.

I know the first thing is to stick on the first line #! /usr/bin/env python but then do I need for example the functions to be in a specific order (i.e., the main one at the top or the bottom). What's more do I need to keep the extension .py for my python file (can I just call the function Dosomething?).

To be short, could you provide a simple guide, the important points someone has to take into account to make a Python file executable?

7条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-05 05:42

Delete the first space. That is,

#!/usr/bin/env python

Should be the very first line of your file. Then, make sure you make set the permisions for the the file to executable with:

chmod u+x your_script.py

Python scripts execute in sequential order. If you have a file filled with functions, common practice is to have something that looks like this at the very end of your file:

if __name__ == '__main__':
    main()

Where main() starts execution of your script. The reason we do it this way, instead of a bare call to main() is that this allows you to make your script act like a module without any modification; if you just had a single line that called main(), your module would would execute the script's main. The if statement just checks if your script is running in the __main__ namespace, i.e., it is running as a script.

查看更多
登录 后发表回答