Python wifi子流程&沟通错误

时间:2017-11-29 20:21:11

标签: python windows subprocess wifi putty

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

我正在使用子进程和管道功能来发送数据,但是当我第二次尝试使用它时,它给出了错误“开始通信后无法发送输入”有人可以指出我做错了吗?

#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

1 个答案:

答案 0 :(得分:1)

似乎你在两个例程中重复使用相同的Network对象。

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

您无法在communicate对象上多次使用subprocess.Popen。如果您想将输入提供给您的程序,您应该:

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

当然不要关闭输入流:

Network.stdin.close()

不要忘记使用换行符

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

我还建议你不要使用stdout=PIPE但是保留默认值(或者使用stdout=DEVNULL重定向到任何内容,这样输出缓冲区就不会被完整和阻塞。