【问题标题】:Subprocess in a threading.Thread hang线程中的子进程。线程挂起
【发布时间】:2012-08-02 18:25:03
【问题描述】:

我不明白为什么下面的代码会挂起。当我从控制台运行它时,一切都很好,但是当我尝试通过浏览器运行它时,页面挂起。 我正在使用 Python 2.7.2。

class MyThread(threading.Thread):
    def __init__(self):
        self.stdout = None
        self.stderr = None
        threading.Thread.__init__(self, name="snapshot",)

    def run(self):
        p = subprocess.Popen(["pwd"], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None)
        p.communicate()

myThread = MyThread()
myThread.start()
myThread.join()

更新 我正在使用 Apache 作为 CGI 运行 Python。运行的系统是 Gentoo 2.1。

我认为问题出在 Apache 上。不知何故,它阻塞了新线程,但我不确定。

【问题讨论】:

  • 语法错误——类定义后没有“:”。
  • “通过浏览器运行”是什么意思?如果您使用的是 Python Web 框架,您应该指定是哪一个,以及您是直接运行它还是在 apache/nginx/etc 后面运行它。

标签: python multithreading apache cgi subprocess


【解决方案1】:

尝试使用shell=False 运行它。

我怀疑当您在 Web 框架中运行此代码时,您实际上并没有 shell,这会导致问题。

或者,您不能从您的 Web 服务器进程中重用 stdoutstdin 并且尝试使用 subprocess.PIPE 这样做会导致事情挂起。

我假设您实际上不需要运行pwd,并且您只是将其用作示例,但如果您真的只需要pwd,这是一种不必要的复杂方法。只需将其替换为 os.curdir 属性即可。

【讨论】:

  • “密码”仅用于测试目的。我尝试使用Shell=False 运行Popen,但没有成功。我还尝试将文件对象传递给stdoutstdin,但该文件只是在没有来自pwd 命令的任何输出的情况下创建的。
猜你喜欢
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 2014-09-15
  • 1970-01-01
相关资源
最近更新 更多