破碎Popen("source the_script.sh")
相當於Popen(["source the_script.sh"])
試圖失敗推出'source the_script.sh'
程序。它無法找到它,因此"No such file or directory"
錯誤。
破碎Popen("source the_script.sh", shell=True)
失敗,因爲source
是一個bash內建命令(在bash型help source
),但默認的shell是/bin/sh
不理解它(/bin/sh
使用.
)。假設可能有其他的bash主義在the_script.sh
,應該使用bash運行:
foo = Popen("source the_script.sh", shell=True, executable="/bin/bash")
由於@IfLoop said,它不是非常有用的一個子進程來執行source
,因爲它可以在不影響父母的環境。
os.environ.update(env)
如果the_script.sh
對某些變量執行unset
,基於方法的失敗。 os.environ.clear()
可以被稱爲重置環境:
#!/usr/bin/env python
import os
from pprint import pprint
from subprocess import check_output
os.environ['a'] = 'a'*100
# POSIX: name shall not contain '=', value doesn't contain '\0'
output = check_output("source the_script.sh; env -0", shell=True,
executable="/bin/bash")
# replace env
os.environ.clear()
os.environ.update(line.partition('=')[::2] for line in output.split('\0'))
pprint(dict(os.environ)) #NOTE: only `export`ed envvars here
它採用env -0
and .split('\0')
suggested by @unutbu
爲了支持任意字節os.environb
,json
模塊可以使用(假設我們使用Python版本,其中"json.dumps not parsable by json.loads" issue是固定的):
爲了避免通過管道傳遞環境,可以將Python代碼更改爲在子進程環境中自行調用,例如:
#!/usr/bin/env python
import os
import sys
from pipes import quote
from pprint import pprint
if "--child" in sys.argv: # executed in the child environment
pprint(dict(os.environ))
else:
python, script = quote(sys.executable), quote(sys.argv[0])
os.execl("/bin/bash", "/bin/bash", "-c",
"source the_script.sh; %s %s --child" % (python, script))
來源
2014-02-28 04:26:58
jfs
[Python中模擬Bash'source']的可能重複(https://stackoverflow.com/questions/3503719/emulating-bash-source-in-python) – sds