破碎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