互联网一遍又一遍地告诉我使用subprocess.Popen和communic()方法来读写子进程的stdin和stdout;但是communic()的文档说它等待程序终止。我正在尝试使用adb shell在手机的相机上打开和关闭视频录制。我希望adb shell进程已经打开,连接到设备,而不是每次运行时都连接。 这不起作用:
>>> import subprocess
>>> adb = subprocess.Popen(["adb", "shell"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> adb.stdin.write('ls/n')
>>> adb.stdout.read()
也不是这样:
>>> adb = subprocess.Popen(["adb", "shell"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> adb.communicate(input=b'ls')
两个都挂了。此命令在终端中按预期运行:
adb shell ls
我在Windows 7 64位,Python 2.7.13上。 我也读过有关pexpect的内容,但它的spawn类在Windows上不起作用。 所以我的问题是如何我可以创建并重复与Windows上的Python 2.7中的子进程通信。 谢谢。
答案 0 :(得分:0)
adb shell shell_command
这会打开一个远程shell,执行shell_command并退出远程shell。
使用python完成同样的事情:
>>> import subprocess
>>> adb = subprocess.Popen(["adb", "shell", "ls"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> out, err = adb.communicate()
如果您只想知道命令是否返回非零返回码:
>>> import subprocess
>>> subprocess.check_call(["adb", "shell", "ls"])