[英]Running Python script through subprocess fails
I am trying to run util.py from script file1.py
using subprocess
. 我试图从脚本运行util.py
file1.py
使用subprocess
。 Both of them are in same directory. 它们都在同一目录中。 When I run them from current directory it works fine, but if I run
file1.py
from different directory it fails. 当我从当前目录运行它们时,它可以正常工作,但是,如果我从其他目录运行
file1.py
,它将失败。
file1.py: file1.py:
#!/usr/bin/env python
import subprocess
out=subprocess.Popen(["./util.py"],shell=True)
print "done"
util.py: util.py:
#!/usr/bin/env python
def display():
print "displaying"
display()
error: 错误:
/bin/sh: ./util.py: No such file or directory
done
Executing ./util.py
in a terminal means "Look in the current working directory for a file named util.py and run it ." 在终端中执行
./util.py
意味着“在当前工作目录中查找名为util.py的文件并运行它 。” The working directory is the directory from where you run the command. 工作目录是您运行命令的目录。 This means that your python script cannot see util.py if you run it from a different directory.
这意味着,如果您从其他目录运行util.py,则python脚本将看不到util.py。
If you are sure that file1.py and util.py always lie in the same directory, you could use __file__
and os.path.dirname
to prefix it with the directory of file1.py: 如果确定file1.py和util.py始终位于同一目录中,则可以使用
__file__
和os.path.dirname
为它添加file1.py目录的前缀:
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")
You can use execfile()
instead of subprocess.Popen()
: 您可以使用
execfile()
代替subprocess.Popen()
:
file1.py: file1.py:
execfile("util.py")
print "done"
or if you want to process both of them,you can use threading
module which is already in python's standard library: 或者如果您想同时处理它们,则可以使用python标准库中已经存在的
threading
模块:
from threading import Thread
Thread(target=lambda:execfile("util.py")).start()
print "done"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.