【问题标题】:Open a child process (adb) in Python 2.7 and interact with it repeatedly without terminating it在 Python 2.7 中打开一个子进程(adb)并反复与它交互而不终止它
【发布时间】:2017-11-20 20:59:35
【问题描述】:

互联网一遍又一遍地告诉我使用 subprocess.Popen 和communicate() 方法来读写子进程的标准输入和标准输出;但是communicate() 的文档说它等待程序终止。我正在尝试使用 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 创建子进程并与子进程重复通信。 谢谢。

【问题讨论】:

    标签: android python windows python-2.7


    【解决方案1】:
    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"])
    

    【讨论】:

    • 谢谢。实际上,我不仅想知道返回码。我想知道如何打开并与子进程反复通信。我自己还没有测试过,但我读过 adb shell 在交互模式下工作得更快;即,每次发送命令时都不必重新启动进程。我不知道打开它是否会更快,但我知道它太慢了。如果我想运行一个一次性进程并在它关闭时收集它的输入,我已经可以使用 os.system 做到这一点。子流程描述提供标准输入,但我没有看到有人使用它。
    猜你喜欢
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 2020-02-08
    • 2014-07-03
    • 2018-10-11
    • 2021-08-19
    相关资源
    最近更新 更多