使用Python脚本中的源命令
我试图从python脚本调用unix中的源命令。我试图通过subprocess.Popen将操作系统环境传递给它来完成它 下面是我执行命令任务的函数:使用Python脚本中的源命令,python,unix,subprocess,Python,Unix,Subprocess,我试图从python脚本调用unix中的源命令。我试图通过subprocess.Popen将操作系统环境传递给它来完成它 下面是我执行命令任务的函数: def run_command(command, tst_env): print tst_env try: p = subprocess.Popen(command, env=tst_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
def run_command(command, tst_env):
print tst_env
try:
p = subprocess.Popen(command, env=tst_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stout, er = p.communicate()
print stout, er
ret = p.wait()
except Exception, e:
print "Exception: ", e
else :
if ret:
print command, "failed", ret
return
else:
print command, "succeeded", ret
return p
tst_env
是os.environ类型的对象
run_命令(source script.sh,os.environ)
说它成功了
但是我无法访问脚本中的函数
情况是这样的:
script.sh如下:
function task_test() {
echo "Test function called"
}
source script.sh
task\u test
将调用shell脚本中的函数
但是我无法从python调用shell脚本中的函数
希望我说的很清楚。子流程是用来执行事情的。它并没有在shell函数和Python之间架起一座桥梁。您不能“加载”shell文件,然后将其视为可以调用的Python对象。您可以只执行脚本的内容。您可以详细说明您无法访问的内容吗。。请回答下一个问题!:)stout和er怎么说?如果shell脚本成功运行,他们应该怎么说?您不需要
p.wait()
-p.communicate()
在子进程退出之前不会返回。p.wait()用于使脚本在运行脚本时等待以获得成功指示。p.communicate用于获取标准消息。我想要的是使用我们编写的shell脚本中的函数。如果在shell中,我们可以使用source命令。但我不能完成它。@GeorgeThomas:不实际,但你可以通过执行这种source file.sh;[功能]
东西。