我正在编写一个包装器来通过 Python(2.7.2)自动化一些 android ADB shell 命令。因为在某些情况下,我需要异步运行命令,所以我使用subprocess .Popen方法来发出 shell 命令。
我遇到了方法[command, args]
参数格式的问题Popen
,其中需要命令/参数拆分在 Windows 和 Linux 之间是不同的:
# sample command with parameters
cmd = 'adb -s <serialnumber> shell ls /system'
# Windows:
s = subprocess.Popen(cmd.split(), shell=False) # command is split into args by spaces
# Linux:
s = subprocess.Popen([cmd], shell=False) # command is a list of length 1 containing whole command as single string
我试过使用shlex .split(),有和没有 posix 标志:
# Windows
posix = False
print shlex.split(cmd, posix = posix), posix
# Linux
posix = True
print shlex.split(cmd, posix = posix), posix
两种情况都返回相同的拆分。
subprocess
是否有正确shlex
处理特定于操作系统的格式的方法?
这是我目前的解决方案:
import os
import tempfile
import subprocess
import shlex
# determine OS type
posix = False
if os.name == 'posix':
posix = True
cmd = 'adb -s <serialnumber> shell ls /system'
if posix: # posix case, single command string including arguments
args = [cmd]
else: # windows case, split arguments by spaces
args = shlex.split(cmd)
# capture output to a temp file
o = tempfile.TemporaryFile()
s = subprocess.Popen(args, shell=False, stdout=o, stderr=o)
s.communicate()
o.seek(0)
o.read()
o.close()
我不认为shlex.split()
在这里做任何事情,并cmd.split()
取得相同的结果。