【发布时间】:2017-06-06 04:23:27
【问题描述】:
我正在开发一个简短的、原生的(不推荐使用外部 [非原生] 模块,例如 pexpect)、跨平台、不安全的 python 远程控制应用程序(Windows 将使用 py2exe 和 exe 文件)。我正在使用 start_new_thread 进行阻塞调用,例如readline()。然而,出于某种原因,我得到了这个丑陋的字符串作为我的输出:
Unhandled exception in thread started by <function read_stream at 0xb6918730>Unhandled exception in thread started by <function send_stream at 0xb69186f0>
Traceback (most recent call last):
Traceback (most recent call last):
File "main.py", line 17, in read_stream
s.send(pipe.stdout.readline())
AttributeError File "main.py", line 14, in send_stream
pipe.stdin.write(s.recv(4096))
AttributeError: 'NoneType' object has no attribute 'stdin'
: 'NoneType' object has no attribute 'stdout'
这是我的程序(main.py):
#!/usr/bin/env python
import socket
import subprocess as sp
from thread import start_new_thread
from platform import system
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.0.0.201', 49200))
shell = 'powershell.exe' if system() == 'Windows' else '/bin/bash' # is this right?
pipe = sp.Popen(shell, shell=True, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
entered_command=False
def send_stream(): # send what you get from command center
while True:
pipe.stdin.write(s.recv(4096))
def read_stream(): # send back what is returned from shell command
while True:
s.send(pipe.stdout.readline())
start_new_thread(send_stream, ())
start_new_thread(read_stream, ())
感谢您的帮助。
【问题讨论】:
-
pipe不能是None。也许你可以删除套接字的东西来创建一个简单的minimal reproducible example -
是的,这表明
pipe是无。在创建的地方插入测试;如果在那里有效,则在线程函数中插入测试 -
确定这个 exact 代码会引发错误吗?我读过
subprocess.Popen构造函数,当出现问题时它会引发异常,但不会返回None。 -
仅供参考,使用
threading.Thread代替低级thread模块。在 Python 3 中,thread被重命名为_thread,以强调它并不是标准库中的公共线程 API。 -
@JoeP 好的,我插入了测试。在函数内部,
pipe没有,但在它们外部是正常的。这有帮助吗?
标签: python file subprocess