[英]interchangeable shebang line in Python script for dual OSes?
A script is developed both on OS X and Windows using a virtualenv. 使用virtualenv在OS X和Windows上都开发了脚本。 The so-called developer has already installed all required packages using a
requirements.txt
file, but one problem remains: 所谓的开发人员已经使用
requirements.txt
文件安装了所有必需的软件包,但是仍然存在一个问题:
If the script is running on OS X, the beginning of each Python file must start like this: 如果脚本在OS X上运行,则每个Python文件的开头都必须这样开始:
#!/Users/os-x-username/.virtualenvs/some_env/bin/python
#!C:\Users\windows-username\Envs\some_env\Scripts\python.exe
But if developing on Windows, the line order must be switched: 但是,如果在Windows上进行开发,则必须切换行顺序:
#!C:\Users\windows-username\Envs\some_env\Scripts\python.exe
#!/Users/os-x-username/.virtualenvs/some_env/bin/python
How can the so-called developer avoid this tediousness? 所谓的开发商如何避免这种乏味?
If you don't mind adding extra steps, ou can create a launcher script launcher.py
like: 如果您不介意添加其他步骤,则可以创建启动器脚本
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
Since this script is there only to run the original_script_name.py
in the desired interpreter for the current platform, it doesn't matter what its shebang is - as long as it picks any Python interpreter it will be fine. 由于该脚本只能在当前平台的所需解释器中运行
original_script_name.py
,因此它的shebang无关紧要-只要选择任何Python解释器就可以了。
It would act as a drop-in replacement for your original script ( original_script_name.py
) so just call launcher.py
instead and it will even redirect the CLI arguments if needed. 它可以代替原始脚本(
original_script_name.py
),因此只需调用launcher.py
,它甚至会在需要时重定向CLI参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.