私はPython(2.7.2)でいくつかのandroid ADBシェルコマンドを自動化するためのラッパーを作成しています。 場合によっては、コマンドを非同期で実行する必要があるため、subprocess.Popenメソッドを使用してシェルコマンドを発行しています。私はshlex .splitを使用してみましたがsubprocess.Popenとshlex.splitのフォーマットは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
:
私は、コマンド/引数の分割が必要とPopen
方法、の[command, args]
パラメータのフォーマットに問題に遭遇してきたが、WindowsとLinuxの間で異なっていますposixフラグの有無にかかわらず、
# Windows
posix = False
print shlex.split(cmd, posix = posix), posix
# Linux
posix = True
print shlex.split(cmd, posix = posix), posix
どちらの場合も同じ分割が返されます。
subprocess
またはshlex
には、OS固有のフォーマットを正しく処理するメソッドがありますか??
これは私の現在のソリューションです:
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()
は、同一の結果を達成します。
あなたは質問に誤字を入れました。 shlexとshelx – jgritty
@jgrittyありがとうございます。修正されました。 –
なぜ 'shell = True'を使うのですか? – jfs