簡體   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