Special characters to be used in subprocess module

Viewed 54

In subprocess module in python,

 subprocess.Popen(
            (
                "git",
                "add",
                "-A",
                "&&",
                "git",
                "commit",
                "-m",
                commit_message
            ),
            cwd=path,
        )

does not work. However if I split it into

 subprocess.Popen(( "git", "add","-A") , cwd=path)

and

subprocess.Popen(( "git", "commit","-m" , "yeah") , cwd=path)

it works. How do I insert "&&" in the middle? Thanks.

2 Answers

The && logical operator is something that the shell (e.g., bash) understands. However, you're executing git which doesn't understand what && means. Explained another way, you're entering the arguments as if you were typing them into a terminal. subprocess.Popen doesn't invoke the shell by default and instead invokes the exec system call with the specified arguments. So, you're telling it to run git with the arguments add, -A (so far, so good), && (git doesn't understand this), git, -m, and yeah.

To execute this as a shell command, you need to add shell=True to subprocess.Popen. Once you do that, you can just type out the command you want as a single string:

subprocess.Popen('git add -A && git commit -m', shell=true, cwd=path)

Only a shell can interpet &&, it's not program or an argument

You can pass shell=True to subprocess.Popen to run your command in a mini-shell like environment, see docs here

Related