Making execution of Python script fool-proof beyond adding shebang
https://softwareengineering.stackexchange.com/questions/382265
-
16-02-2021 - |
题
Assume that a Python package (available via PyPI) is too difficult for novice users to utilize. Specifically, typing python2 path_to_package/start_GUI.py
in the command line, which opens a TKinter GUI, is too hard for many users. Instead, users would like to simply double-click on the file start_GUI.py
, irrespective of the operating system they are on.
Beyond placing a shebang (i.e., #!/usr/bin/env python2
) at the very top of the Python script start_GUI.py
, how else can I make it easier for users to execute it?
Linux/OSX:
Users on Linux/OSX could double-click start_GUI.py
if they first changed its file permissions (i.e., chmod +X start_GUI.py
). Is it possible to change the file permissions of start_GUI.py
during the installation of the package via setup.py
?
Windows:
Users on Windows could double-click a batch file (e.g., start_GUI.bat
), which in turn calls start_GUI.py
. Minimal example of start_GUI.bat
:
ECHO ON
REM A batch script to execute the GUI
SET PATH=%PATH%;C:\path_to_python\Python27
python path_to_package\start_GUI.py
PAUSE
Can I have this batch file written during the installation of the package via setup.py
?
解决方案
Users should not have to write any launcher scripts, which is why setuptools
can create them for you with the entry_points
key. For example:
setup(
...,
entry_points={
'console_scripts': [
'myprogram=mypackage:main',
],
},
)
This would create an executable myprogram
in a format appropriate for the target operating system that basically does:
import sys
from mypackage import main
sys.exit(main())
For further info, read Automatic Script Creation in the setuptools docs.