[英]Is there a way to make python subprocess not terminate after running through the script once?
[英]Running Python script through subprocess fails
我试图从脚本运行util.py file1.py
使用subprocess
。 它们都在同一目录中。 当我从当前目录运行它们时,它可以正常工作,但是,如果我从其他目录运行file1.py
,它将失败。
file1.py:
#!/usr/bin/env python
import subprocess
out=subprocess.Popen(["./util.py"],shell=True)
print "done"
util.py:
#!/usr/bin/env python
def display():
print "displaying"
display()
错误:
/bin/sh: ./util.py: No such file or directory
done
在终端中执行./util.py
意味着“在当前工作目录中查找名为util.py的文件并运行它 。” 工作目录是您运行命令的目录。 这意味着,如果您从其他目录运行util.py,则python脚本将看不到util.py。
如果确定file1.py和util.py始终位于同一目录中,则可以使用__file__
和os.path.dirname
为它添加file1.py目录的前缀:
file1.py:
#!/usr/bin/env python
import os
import subprocess
current_dir = os.path.dirname(__file__)
filename = os.path.join(current_dir, "util.py")
out = subprocess.Popen([filename], shell=True)
print("done")
您可以使用execfile()
代替subprocess.Popen()
:
file1.py:
execfile("util.py")
print "done"
或者如果您想同时处理它们,则可以使用python标准库中已经存在的threading
模块:
from threading import Thread
Thread(target=lambda:execfile("util.py")).start()
print "done"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.