Sto scrivendo un wrapper per automatizzare alcuni comandi della shell ADB di Android tramite Python (2.7.2). Poiché, in alcuni casi, ho bisogno di eseguire il comando in modo asincrono, sto usando il metodo subprocess. Open per emettere comandi di shell.subprocess.Popen e shlex.split formattazione in windows e linux
ho incontrato un problema con la formattazione del parametro [command, args]
del metodo Popen
, dove ci richiedono di comando/args spaccatura è diverso tra Windows e 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
Ho provato con shlex .split(), con e senza il flag posix:
# Windows
posix = False
print shlex.split(cmd, posix = posix), posix
# Linux
posix = True
print shlex.split(cmd, posix = posix), posix
Entrambi i casi restituiscono lo stesso split.
Esiste un metodo in subprocess
o shlex
che gestisce i formati specifici del sistema operativo correttamente?
Questa è la mia soluzione attuale:
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()
non credo shlex.split()
sta facendo nulla qui, e cmd.split()
ottiene risultati identici.
Hai fatto un errore di battitura nella domanda. shlex vs shelx. – jgritty
@jgritty grazie. Corretto. –
perché usi 'shell = True'? – jfs