我希望能够启动、停止并获得另一个python程序的控制台输出。我不想在当前程序中运行它,我希望它们作为两个独立的实例运行。
这两个文件都在同一个目录中。
我看过关于如何获取另一个python程序的控制台输出,以及如何启动和停止它的指南,但我还没有找到关于这两个方面的指南。
我还应该注意,我想要输出的文件是一个.pyw文件。
谢谢。
编辑:不是复制品,它不是那么简单...
EDIT2:
这是我的尝试
main.py
import subprocess
p = subprocess.Popen(['python', 'sub.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# continue with your code then terminate the child
with p.stdout:
for line in iter(p.stdout.readline, b''):
print(line)
p.wait()
sub.py
import time
for i in range(100):
print(i)
time.sleep(1)
它在某种程度上是有效的,但它会像这样打印出来
b'0\r\n‘b'1\r\n’b'2\r\n‘b'3\r\n’b'4\r\n‘
EDIT3:
import subprocess
p = subprocess.Popen(['python', 'sub.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
with p.stdout:
for line in iter(p.stdout.readline, b''):
print(line.decode("utf-8").replace("\r\n", ""))
p.wait()
这是最好的方法吗?
然而,我仍然有一些问题。我希望完全单独运行该程序,因此我应该能够同时运行main.py
程序中的其他代码,但这不起作用。
import subprocess
import time
def get_output():
p = subprocess.Popen(['python', 'sub.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
with p.stdout:
for line in iter(p.stdout.readline, b''):
print(line.decode("utf-8").replace("\r\n", ""))
p.wait()
def print_stuff():
for i in range(100):
print("." + str(i))
time.sleep(1)
if __name__ == "__main__":
get_output()
print_stuff()
import time
def main():
for i in range(100):
print(i)
time.sleep(1)
if __name__ == "__main__":
main()
EDIT4:是我尝试同时运行这两个程序的尝试
import subprocess
import asyncio
async def get_output():
p = subprocess.Popen(['python', 'sub.py', 'watch', 'ls'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
with p.stdout:
for line in iter(p.stdout.readline, b''):
print(line.decode("utf-8").replace("\r\n", ""))
p.wait()
async def print_stuff():
for i in range(100):
print("." + str(i))
await asyncio.sleep(1)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(
print_stuff(),
get_output()
))
loop.close()
import asyncio
async def main():
for i in range(100):
print(i)
await asyncio.sleep(1)
if __name__ == "__main__":
asyncio.run(main())
预期输出为
.0 0 .1 1 .2 2...
但是输出结果是
.0 0 1 2 3 4 5 ...
EDIT5:我认为问题在于subprocess.Popen
持有程序,所以我认为我需要使用asyncio.create_subprocess_exec
m,但我不能准确地弄清楚如何让它工作。
发布于 2019-06-04 01:57:08
当我问了一个类似的问题时,下面是我是如何做到的。输出一打印出来,我就需要它,而不是等待缓冲区填充。
子进程
from time import sleep
# Dummy child process for popen demonstration
# Print "sleeping" at 1-sec intervals, then a "QUIT" message.
for _ in range(5):
print(_, "sleeping")
sleep(1)
print("Child process finishes")
父进程
import subprocess
import time
# Turn off output buffering in Python;
# we need each output as soon as it's printed.
environ["PYTHONUNBUFFERED"] = "1"
# Locate the child's source file -- YOU can use a local path.
branch_root = environ["PYTHONPATH"]
cmd = ["/usr/bin/python3", branch_root + "popen_child.py"]
# Start the child process, opening a pipe from its stdout
# Include stderr under stdout.
test_proc = subprocess.Popen(
cmd,
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
print(time.time(), "START")
# Catch and print the output as it's generated.
for out_data in iter(test_proc.stdout.readline, ""):
print(time.time(), out_data, end="")
print("TEST completed")
在父进程中,打开和关闭“侦听”是一个需要注意的问题。
发布于 2019-06-04 01:40:03
对于最初的评论,我很抱歉。
我知道一种方法,但我不确定它是否在所有操作系统上都有效。它涉及到subprocess
模块:
import subprocess
import os
#another python file with possible inputs
command = "python3 test2.py"
#get current file dir as thats where test2.py is located
fileDir = os.path.dirname(os.path.realpath(__file__))
#gets outputs printed on the terminal
process = subprocess.check_output(command.split(), cwd=fileDir)
print(process)
这种方法还可以确保在继续主代码之前完成第二个脚本。
编辑:输出为字节形式,使用类似process.decode('utf-8')
的格式进行解码
更多here
https://stackoverflow.com/questions/56431877
复制相似问题