Note that there are some explanatory texts on larger screens.

plurals
  1. POsubprocess.Popen and shlex.split formatting in windows and linux
    text
    copied!<p>I am writing a wrapper to automate some android ADB shell commands via Python (2.7.2). Since, in some cases, I need to run the command asynchronously, I am using the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a>.Popen method to issue shell commands.</p> <p>I have run into a problem with the formatting of the <code>[command, args]</code> parameter of the <code>Popen</code> method, where there require command/args split is different between Windows and Linux:</p> <pre><code># sample command with parameters cmd = 'adb -s &lt;serialnumber&gt; 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 </code></pre> <p>I have tried using <a href="http://docs.python.org/library/shlex.html" rel="nofollow">shlex</a>.split(), with and with out the posix flag:</p> <pre><code># Windows posix = False print shlex.split(cmd, posix = posix), posix # Linux posix = True print shlex.split(cmd, posix = posix), posix </code></pre> <p>Both cases return the same split.</p> <p>Is there a method in <code>subprocess</code> or <code>shlex</code> that handles the OS-specific formats <em>correctly</em>?</p> <p><strong>This is my current solution:</strong></p> <pre><code>import os import tempfile import subprocess import shlex # determine OS type posix = False if os.name == 'posix': posix = True cmd = 'adb -s &lt;serialnumber&gt; 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() </code></pre> <p>I don't think <code>shlex.split()</code> is doing anything here, and <code>cmd.split()</code> achieves identical results.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload