【问题标题】:Python 3 failing to send message to C# subprocessPython 3 无法向 C# 子进程发送消息
【发布时间】:2018-06-19 15:28:22
【问题描述】:

python 新手,目前使用的是 Python 3.5.2。我有一个子进程,我需要在其中监视输出,对其进行处理并通过 kivy 显示它。这工作正常。

但是有一点,子进程需要回复才能继续或退出。这就是我完全陷入困境的地方。

chimp_cmd = 'sudo /usr/bin/mono ' + os.getcwd() + '/aDotNet.exe ' + aVeryLongListofParam    # aVeryLongListofParam is read from a file
child = subprocess.Popen([chimp_cmd], 
                                        shell=True, 
                                        stdout=subprocess.PIPE, 
                                        stderr=subprocess.STDOUT,
                                        stdin=subprocess.PIPE,
                                        bufsize=0) # no difference with bufsize set to 1
 # while loop that reads in the data    

     # do funky stuff with the output data, (this works and relies on a lot of starts with comparisons)

     if ( (b''.join(MyOutputLineList).decode("utf-8) ).startswith("Would you like"):

         # wait for the thread that gets the response - this works

         if usrReply = UsrKeyReply.no:
             print("received user no")        # we get to here 
             # attempts at sending a reply:
             ret_value = child.stdin.write(b'n\n') # this doesn't work for me
             print(ret_value)
             print("test1") 
             os.system('pidof mono')        # for debug

         elif usrReply = UsrKeyReply.yes:
             print("received user yes")  # also get to this point 
             stdout, stderr = child.communicate(input=b'n\n')[0]
             # child.stdin.flush()  <-- this hangs the code
             print("test2")                 # doesn't work for me either

其他细节。 在 Ubuntu 上。 使用以下命令调用 python 脚本:

sudo python3 myscript.py    

是的,它必须是 sudo,因为单声道需要访问 USB 端口。

DotNet.exe 是第三方

如果直接从命令行调用,DotNet.exe 可以正常工作。

我知道消息不会返回到子进程,因为除了没有任何反应之外,我可以打开另一个终端并通过以下方式监视子进程:

sudo strace -p <mono's PID>

在这里,我可以看到 exe 正在运行并与 python 脚本很好地配合,我看到提示“你愿意...”

当 python 脚本到达发送回复的点时,孩子不会终止(当 'n' 时)或继续(当 'y' 时)

救命!

按照@Hermann 的建议,我尝试更改为:

bufsize=1,
universal_newlines=True)

还修改了对

的回复
stdout, stderr = child.communicate(input='n\n')[0]
child.stdin.flush()

脚本在此之后挂起。

还有什么想法吗?

【问题讨论】:

    标签: c# python subprocess


    【解决方案1】:

    您可以通过调用 child.stdin.flush() 显式刷新写入缓冲区。

    或者,您可以尝试在您的subprocess.Popen 调用中添加bufsize=1 和universal_newlines=True 以切换行缓冲模式。请注意,如subprocess stdin buffer not flushing on newline with bufsize=1 中的各种 cmets 中所述,Python 3 版本的行为差异很大。

    【讨论】:

    • 感谢您的回复,但对这些建议都不满意。
    【解决方案2】:

    经过进一步调查,发现python确实向子进程发送数据。问题在于如何在 C# 端处理输入。

    Console.ReadKey().Key /* this will not work with python subprocess piped stdin */
    

    对

    piped_reply = Console.ReadLine() /* will work with python piped stdin */
    

    查看 SO 问题:C# Console receive input with pipe

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    相关资源
    最近更新 更多