繁体   English   中英

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

[英]interchangeable shebang line in Python script for dual OSes?

使用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

所谓的开发商如何避免这种乏味?

如果您不介意添加其他步骤,则可以创建启动器脚本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解释器就可以了。

它可以代替原始脚本( original_script_name.py ),因此只需调用launcher.py ,它甚至会在需要时重定向CLI参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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