Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curly Braces in python Popen

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
like image 535
memecs Avatar asked Mar 26 '14 11:03

memecs


People also ask

What do {} do in Python?

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.

Can you use curly braces in Python?

Easily my favorite advanced feature in Python, rather than relying on whitespace to denote scopes (boring) — we can use curly braces!

What is Popen in Python?

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'.

How do you make a set with curly braces in Python?

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.


2 Answers

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')
like image 147
jfs Avatar answered Oct 18 '22 21:10

jfs


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.

like image 27
venpa Avatar answered Oct 18 '22 21:10

venpa