Computer Science Atlas
Snippets

Python 3: Using Shell Syntax with subprocess.run()

Part 5 of a Series: subprocess.run()
September 3, 2021
 
Articles in Series: subprocess.run()
  1. Python 3: Execute a System Command Using subprocess.run()
  2. Python 3: Get and Check Exit Status Code (Return Code) from subprocess.run()
  3. Python 3: Get Standard Output and Standard Error from subprocess.run()
  4. Python 3: Standard Input with subprocess.run()
  5. Current Article
    Python 3: Using Shell Syntax with subprocess.run()
  6. Python 3: Specify Environment Variables in subprocess.run()

We can pass in an entire shell command (command name + arguments) as a single string using the run() option shell=True:

from subprocess import run

run( 'echo "Hello, world!"', shell=True )
1
2
3
from subprocess import run

run( 'echo "Hello, world!"', shell=True )

This code has the same effect as run( [ 'echo', 'Hello, world!' ] ).

Using shell=True allows us to use the system's shell operator syntax like > and |. For example, on Linux or macOS, we can run:

from subprocess import run

run( 'curl https://example.com 2>/dev/null | grep iana',
     shell=True )
1
2
3
4
from subprocess import run

run( 'curl https://example.com 2>/dev/null | grep iana',
     shell=True )