Running subprocess won't handle curly braces correctly
# Python 2.7.4
import subprocess
subprocess.Popen('ls src/*.cpp',shell=True):
src/tonemap.cpp src/pch.cpp
subprocess.Popen('ls src/{t,p}*.cpp', shell=True)
ls: cannot access src/{p,t}*.cpp: No such file or directory
The same program will work on a different machine with python 2.7.2. Both systems use bash shells.
Do you the reason and how can I fix it?
EDIT:
Invoking the command directly from the command line returns the correct result:
ls src/{t,p}*.cpp
src/tonamep.cpp src/pch.cpp
In languages like C curly braces ( {} ) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.
Easily my favorite advanced feature in Python, rather than relying on whitespace to denote scopes (boring) — we can use curly braces!
Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.
Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section. Show activity on this post. You need to do empty_set = set() to initialize an empty set.
shell=True
runs /bin/sh
that doesn't support this syntax. Specify bash
explicitly:
from subprocess import check_call
check_call('ls src/{t,p}*.cpp', shell=True, executable='/bin/bash')
In your case, Popen executed correctly, error is reported from ls
.
It should give same error when you execute the command:
ls src/{t,p}*.cpp
in terminal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With