Python wifi 子进程和通信错误

Python wifi subprocess & communication errors

我正在尝试通过 wifi 连接到 romba 机器人。我已经成功地能够使用以下代码打开 cmd 并连接到 wifi 并发送其密码。这将成功连接机器人和计算机。我的问题是当我尝试发送附加信息时。我一次只尝试传递一个字符。

我正在使用子进程和管道功能发送数据,但是当我第二次尝试使用它时,出现错误"Cannot send input after starting communication"有人可以指出我做错了什么吗?

#Connects the the desired WiFi network.         
def connect_to_network(name):

    global Network
    #global Putty

    Network = Popen('netsh wlan connect ' + str(name), shell=True, stdout=PIPE, stderr=STDOUT, stdin=PIPE)

    password = "password"
    Network.communicate(input=password.encode('utf-8'))
    Network.stdin.close()

     #Putty = Application(backend="uia").start('putty.exe -raw 192.168.1.1')



#Sends out character to BOT via WiFi.
def WiFi_Send(action):

    global Network
    #global Putty

    clear_output()

    print("Sending: " + str(action))

    #PACKET TO SEND
    packet = ""

    if(action == "SCAN"):
        packet = "S"
    elif(action == "MOVE FORWARD"):
        packet = "F"
    elif(action == "TURN LEFT"):
        packet = "L"
    elif(action == "TURN RIGHT"):
        packet = "R"

     Network.communicate(input=packet.encode('utf-8'))
     Network.stdin.close()

输出:

Sending: SCAN
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-c2f5d752b649> in <module>()
    341 #   call in value. (Waits for it to start)
    342 if __name__ == "__main__":
 -->343    main()

<ipython-input-2-c2f5d752b649> in main()
    326                     buttonFlag = 0
    327                     actionComplete = True
--> 328                     WiFi_Send(action)
    329                     break
330                 elif(B_button):

<ipython-input-2-c2f5d752b649> in WiFi_Send(action)
    172         packet = "R"
    173 
--> 174     Network.communicate(input=packet.encode('utf-8'))
    175     Network.stdin.close()
    176 

~\Anaconda3\lib\subprocess.py in communicate(self, input, timeout)
    811 
    812         if self._communication_started and input:
--> 813             raise ValueError("Cannot send input after starting 
communication")
    814 
    815         # Optimization: If we are not worried about timeouts, we haven't

ValueError: Cannot send input after starting communication

您似乎在两个例程中重用了相同的 Network 对象。

问题是 communicate 只能工作一次。这是一种获取单独的输出和错误流并隐藏使用这些流时避免死锁的复杂性的便捷方法。

您不能在一个 subprocess.Popen 对象上多次使用 communicate。如果你想为你的程序提供输入,你应该这样做:

Network.stdin.write(password.encode('utf-8'))

当然不要关闭输入流:

Network.stdin.close()

别忘了换行

Network.stdin.write(b"\n")

我还建议您不要使用 stdout=PIPE 而保留默认值(或使用 stdout=DEVNULL 重定向到空,这样输出缓冲区就不会变满并阻塞。