用于双操作系统的Python脚本中可互换的shebang行?

时间:2017-12-06 23:33:38

标签: python shebang

使用virtualenv在OS X和Windows上开发脚本。所谓的开发人员已经使用requirements.txt文件安装了所有必需的包,但仍然存在一个问题:

如果脚本在OS X上运行,则每个Python文件的开头必须如下所示:

#!/Users/os-x-username/.virtualenvs/some_env/bin/python
#!C:\Users\windows-username\Envs\some_env\Scripts\python.exe

但如果在Windows上开发,则必须切换行顺序:

#!C:\Users\windows-username\Envs\some_env\Scripts\python.exe
#!/Users/os-x-username/.virtualenvs/some_env/bin/python

所谓的开发者怎么能避免这种单调乏味?

1 个答案:

答案 0 :(得分:1)

如果您不介意添加额外的步骤,您可以创建一个启动器脚本launcher.py,如:

#!/usr/bin/env python

import subprocess
import sys

if __name__ != "__main__":
    print("This is a launcher. Please run only as a main script.")
    exit(-1)

INTERPRETERS = {
    "win": r"C:\Users\windows-username\Envs\some_env\Scripts\python.exe",  # Windows
    "darwin": "/Users/os-x-username/.virtualenvs/some_env/bin/python",  # OSX
    "linux": "/home/linux-user/.virtualenvs/some_env/bin/python"  # Linux
    # etc.
}

TARGET_SCRIPT = "original_script_name.py"

interpreter = None
for i in INTERPRETERS:  # let's find a suitable interpreter for the current platform
    if sys.platform.startswith(i):
        interpreter = i
        break
if not interpreter:
    print("No suitable interpreter found for platform:", sys.platform)
    exit(-1)

main_proc = subprocess.Popen([interpreter, TARGET_SCRIPT] + sys.argv[1:])  # call virtualenv
main_proc.communicate()  # wait for it to finish

exit(main_proc.poll())  # redirect the return code

由于此脚本仅用于在当前平台的所需解释器中运行original_script_name.py,因此它与shebang的关系并不重要 - 只要它选择任何Python解释器就可以了。< / p>

它将作为原始脚本(original_script_name.py)的替代品,因此只需调用launcher.py即可,如果需要,它甚至可以重定向CLI参数。