【问题标题】:python and threading- code after thread.start() not being ran -- code stops未运行 thread.start() 之后的 python 和线程代码 - 代码停止
【发布时间】:2017-12-14 02:45:17
【问题描述】:

我正在尝试让这个函数运行:

def local_server():

    # Start local
    unix_python_bin = "py_env/bin/python"
    unix_script_file = "./run.py"

    win_python_bin = "win_py_env/Scripts/python"
    win_script_file = "./run.py"

    try:

        system = platform.system()
        if "windows" in system.lower():
            theproc = subprocess.Popen([win_python_bin, win_script_file])
            theproc.communicate()
        else:
            subprocess.Popen([unix_python_bin, unix_script_file])

        set_server_connected(True)

    except:

        set_server_connected(False)

作为线程,因为此进程启动 localhost 服务器并占用终端,导致用户必须按 Ctrl+C 才能关闭 localhost。我想让 localhost 在后台启动并继续运行,因为 python 应用程序将与之交互。

到目前为止,我使用以下方法调用该函数:

server = Thread(target = local_server)
server.start()

调用有效,本地主机启动,但代码永远不会到达 set_server_connected()。终端也被服务器挂起,等待 Ctrl+C。

我怎样才能让这段代码不间断地运行?

【问题讨论】:

  • communicate() 将阻塞直到子进程结束。这就是你想要的吗?
  • 不,我希望它运行 python 脚本,并且在该脚本运行时继续执行代码并到达 set_server_connected(True) communicate() 是 Windows 操作系统版本的命令,它会像你一样说,阻塞直到它结束,并且命令的unix版本的subprocess.Popen也这样做。我希望两者都运行脚本并且在它们结束之前不阻塞。
  • 昨晚我在使用 mac 并且 Popen 也被阻塞了。今天我在 Windows 上,我将 Windows 代码更改为 Popen 调用 subprocess.Popen([win_python_bin, win_script_file]) 并且子进程仍然阻塞(卡在等待进程结束)。我正确使用 subprocess.Popen() 吗?看文档,好像是我。

标签: python multithreading flask localhost subprocess


【解决方案1】:

在阅读了关于 subprocess 的文档后,我添加了以下内容:

from subprocess import Popen, PIPE

和变化:

    if "windows" in system.lower():
        theproc = subprocess.Popen([win_python_bin, win_script_file])
        theproc.communicate()
    else:
        subprocess.Popen([unix_python_bin, unix_script_file])

    set_server_connected(True)

到这里:

   if "windows" in system.lower():
        p = Popen([win_python_bin, win_script_file], stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = False)
   else:
        p = Popen([unix_python_bin, unix_script_file], stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = False)

【讨论】:

    猜你喜欢
    • 2012-02-27
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多