【问题标题】:How can I use run instead of communicate when providing text on stdin?在标准输入上提供文本时如何使用运行而不是通信?
【发布时间】:2020-11-09 17:02:57
【问题描述】:

试图弄清楚如何做到这一点:

command = f"adb -s {i} shell"
proc = Popen(command, stdin=PIPE, stdout=PIPE)
out, err = proc.communicate(f'dumpsys package {app_name} | grep version'.encode('utf-8'))

但是在这个:

command = f"adb -s {i} shell"
proc = run(command, stdin=PIPE, stdout=PIPE, shell=True)
out, err  = run(f'dumpsys package {app_name} | grep version', shell=True, text=True, stdin=proc.stdout )

这个想法是创建一个需要某种输入的命令(例如(进入 shell)),然后将另一个命令插入到 shell。 我找到了一种在线交流的方法,但我想知道如何使用 run() func 来做到这一点。 谢谢!

【问题讨论】:

  • 请阅读PEP-8= 周围应仅在赋值中使用空格,而不是关键字参数。

标签: python python-3.x shell cmd adb


【解决方案1】:

您只需调用一次run -- 在input 参数中传递远程命令(不要在不需要的地方使用shell=True)。

import subprocess, shlex
proc = subprocess.run(['adb', '-s', i, 'shell'],
                      capture_output=True,
                      input=f'dumpsys package {shlex.quote(app_name)} | grep version')

shlex.quote 防止包含$(...); 等的应用名称在您的设备上运行不需要的命令。

【讨论】:

    猜你喜欢
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    相关资源
    最近更新 更多