我希望能够启动,停止并获取另一个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,但我无法弄清楚如何使它正常工作。
答案 0 :(得分:1)
当我问类似的问题时,这就是我的做法。我还需要在打印输出后立即输出, not 等待缓冲区填充。
孩子的过程
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")
打开和关闭“监听”是父流程中的一个注意事项。
答案 1 :(得分:0)
很抱歉,最初的评论。
我知道一种方法,但不确定在所有操作系统上都可以使用。它涉及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