python子进程的输出不可见_Python子进程输出不正确?

这里的问题是你正在向进程发送SIGINT.如果你只是关闭stdin,nc将关闭它的套接字并退出,这就是你想要的.

听起来你真的在实际程序中使用nc作为客户端(虽然不是服务器),这意味着你有两个简单的修复:

而不是lookup_client.send_signal(subprocess.signal.SIGINT),只需执行lookup_client.stdin.close(). nc会在输入中将其视为EOF,并正常退出,此时服务器也将退出.

#!/usr/bin/env python

import subprocess

lookup_server = subprocess.Popen("nc -l 5050", shell=True)

lookup_client = subprocess.Popen("nc localhost 5050", shell=True, stdin=subprocess.PIPE)

print lookup_client.poll()

lookup_client.stdin.write("magic

")

lookup_client.stdin.close()

print lookup_client.poll()

lookup_server.wait()

print "Lookup server terminated properly"

当我运行它时,最常见的输出是:

None

None

magic

Lookup server terminated properly

偶尔第二个None代替0,和/或它是在魔术之后而不是之前,但除此之外,它总是全部四行. (我在OS X上运行.)

对于这个简单的情况(虽然可能不是你的真实情况),只需使用communicate而不是手动尝试.

#!/usr/bin/env python

import subprocess

lookup_server = subprocess.Popen("nc -l 5050", shell=True)

lookup_client = subprocess.Popen("nc localhost 5050", shell=True, stdin=subprocess.PIPE)

print lookup_client.communicate("magic

")

lookup_server.wait()

print "Lookup server terminated properly"

与此同时:

Also, if I change the first argument of Popen to an array of all of those arguments, none of the nc calls execute properly and the script runs through without ever waiting. Why does that happen?

On Unix with shell=True… If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.

所以,subprocess.Popen([“nc”,“ – l”,“5050”],shell = True)/ bin / sh -c’nc’-l 5050,sh不知道如何处理这些参数.

你可能想要使用一个args数组,但是你必须摆脱shell = True – 无论如何这都是个好主意,因为shell在这里没有帮助你.

还有一件事:

lookup_client.send_signal(subprocess.signal.SIGINT)

print lookup_client.poll()

这可能会打印-2或None,具体取决于客户端是否已完成对SIGINT的响应并在轮询之前被杀死.如果你想真正获得-2,你必须调用wait而不是poll(或做其他事情,比如循环直到poll返回非None).

最后,为什么原始代码不起作用?好吧,发送SIGINT是异步的;它无法保证何时生效.对于可能出错的一个例子,它可以在客户端甚至打开套接字之前生效,在这种情况下,服务器仍然在等待从未出现的客户端.

您可以在信号调用之前输入time.sleep(5)来测试它 – 但显然这不是真正的修复,甚至是可接受的黑客攻击;它只对测试问题有用.你需要做的就是杀死客户端,直到它完成了你想做的一切.对于复杂的情况,你需要建立一些机制来做到这一点(例如,阅读它的标准输出),而对于简单的情况,沟通已经是你需要的一切(并且没有理由首先杀死孩子).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值