我正在尝试运行此功能:
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)
作为线程,因为此进程启动本地主机服务器并占用终端,导致用户必须按Ctrl + C关闭本地主机。我希望在后台启动localhost并继续运行,因为python应用程序将与它进行交互。
截至目前,我将该功能称为:
server = Thread(target = local_server)
server.start()
调用有效,localhost启动但代码永远不会到达set_server_connected()。终端也由服务器等待Ctrl + C保持。
如何在不停止的情况下运行此代码?
答案 0 :(得分:0)
在阅读了子流程上的文档后,我通过添加:
来实现它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)