Subprocess.Popen and shlex.split formatting in windows and linux

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:

# 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

I tried using shlex .split (), with and without the posix sign:

# Windows
posix = False
print shlex.split(cmd, posix = posix), posix
# Linux
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

# 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() .

+5
2

, , , shell=True

:

Unix = True: args - , . , , . , , . args - , , . , Popen :

Popen (['/bin/sh', '-c', args [0], args [1],...])

http://docs.python.org/library/subprocess.html

+5

shell=True , , Windows Cmd.exe; Linux , , /bin/bash, (zsh, tcsh ..). , , , -.

shell=True, . - :

cmd = 'adb -s <serialnumber> shell ls /system'
s = subprocess.Popen(cmd.split())  # shell=False by default
+4

All Articles