Python(2.7.2)を介していくつかのAndroidADBシェルコマンドを自動化するラッパーを作成しています。場合によっては、コマンドを非同期で実行する必要があるため、サブプロセス.Popenメソッドを使用してシェルコマンドを発行しています。
[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
posixフラグを使用して、または使用せずに、 shlex .split()を使用してみました。
# Windows
posix = False
print shlex.split(cmd, posix = posix), posix
# Linux
posix = True
print shlex.split(cmd, posix = posix), posix
どちらの場合も同じ分割を返します。
OS固有のフォーマットを正しく処理する方法はあります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()
同じ結果が得られます。