Adding paths to arguments in popen
<p>I want to execute a Linux command through Python. This works in the terminal:</p>

<p><code>/usr/bin/myprogram --path "/home/myuser"</code></p>

<p>I've tried this:</p>

<pre><code>path = "/home/myuser"
args = ['/usr/bin/myprogram', '--path ' + path]
proc = subprocess.Popen(args)
</code></pre>

<p>And this:</p>

<pre><code>path = "/home/myuser"
args = ['/usr/bin/myprogram', '--path "' + path + '"']
proc = subprocess.Popen(args)
</code></pre>

<p>But <code>myprogram</code> does not accept the path formatting. I know that paths behave differently when not executing as shell but I can't get it working. I've also tried single quoting the path instead of double quoting it. Bonus points for a solution that also works on Windows (with a different program path, obviously).</p>

<p>EDIT: Sorry, was writing this out from memory and used backslashes instead of forward slashes. The actual code did use the (correct) forward slashes.</p>

<p>The problem comes from your string literal, <code>'\usr\bin\myprogram'</code>. According to <a href="https://docs.python.org/2.0/ref/strings.html" rel="nofollow">escaping rules</a>, <code>\b</code> is replaced by <code>\x08</code>, so your executable is not found.</p>

<p>Pun an <code>r</code> in front of your string literals (i.e. <code>r'\usr\bin\myprogram'</code>), or use <code>\\</code> to represent a backslash (i.e. <code>'\\usr\\bin\\myprogram'</code>).</p>

python linux python-2.7