I am writing a wrapper to automate some Android ADB shell commands through Python (2.7.2). Since in some cases I need to run the command asynchronously, I use the subprocess .Popen method to issue shell commands.
I had a problem formatting a [command, args]method parameter Popen, which requires splitting the / args command between Windows and Linux:
cmd = 'adb -s <serialnumber> shell ls /system'
s = subprocess.Popen(cmd.split(), shell=False) # command is split into args by spaces
s = subprocess.Popen([cmd], shell=False) # command is a list of length 1 containing whole command as single string
I tried using shlex .split (), with and without the posix sign:
posix = False
print shlex.split(cmd, posix = posix), posix
posix = True
print shlex.split(cmd, posix = posix), posix
Both cases return the same split.
Is there a method in subprocessor shlexthat handles OS formats correctly?
This is my current solution:
import os
import tempfile
import subprocess
import shlex
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)
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() .