在stdin上提供文本时,如何使用run而不是communication



试图找出如何做到这一点:

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。谢谢

您只需要调用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可防止包含$(...);等的应用程序名称在您的设备上运行不需要的命令。

最新更新