运行 Python 通过子进程的脚本失败

Running Python script through subprocess fails

我正在尝试使用 subprocess 从脚本 file1.py 运行 util.py。它们都在同一个目录中。当我从当前目录 运行 它们工作正常,但如果我从不同目录 运行 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 意味着 "Look in the current working directory for a file named util.py and run it." 工作目录是您 运行 命令所在的目录。这意味着如果您 运行 来自不同的目录,您的 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"

或者如果你想同时处理它们,你可以使用 threading 模块,它已经在 python 的标准库中:

from threading import Thread

Thread(target=lambda:execfile("util.py")).start()  
print "done"