首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >发送stdout和stderr而不等待进程结束

发送stdout和stderr而不等待进程结束
EN

Stack Overflow用户
提问于 2021-10-04 14:36:38
回答 1查看 66关注 0票数 0

如果我设置command1 = "start notepad.exe“,有没有一种方法可以让脚本输出gino.stdout和gino.stderr,而不等待notepad.exe关闭?

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

发布于 2021-10-04 15:23:18

令我惊讶的是,这比我预期的要难一些。我假设你的命令是notepad.exe,并且我假设你在windows上,所以像stdbuf这样的工具是不可用的。

从刷新stdout的程序中获取输出很容易:

代码语言:javascript
复制
# tesflush.py
import time
from sys import stdout

for i in range(100):
    print(f"line {i}")
    stdout.flush()
    time.sleep(0.1)
代码语言:javascript
复制
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的简单方法,从而强制输出刷新:

代码语言:javascript
复制
#testnoflush.py
import time

for i in range(100):
    print(f"line {i}")
    time.sleep(0.1)
代码语言:javascript
复制
import pexpect

child = pexpect.spawn("python test2.py", encoding="utf8")
for line in child:
    print(line, end="")
child.close()

我怀疑你会需要这样的东西(如果你真的需要避免pexpect,链接的问题有一个手动实现)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69437839

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档