DenverCoder10 DenverCoder10 - 1 year ago 58
Bash Question

Why does this valid shell command throw an error in python via subprocess?

The line

awk -F'[][]' '/dB/ { print $2 }' <(amixer sget Master)
in bash returns my system's current volume (e.g. "97%").

I tried to incorporate this in Python 3

#!/usr/bin/env python3
import subprocess
command = "awk -F'[][]' '/dB/ { print $2 }' <(amixer sget Master)"
output = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)


However the output from the shell returns

/bin/sh: 1: Syntax error: "(" unexpected

Why does this fail and how do I fix my code?

Answer Source

Because you are using bashism in form of a process substitution, and your /bin/sh doesn't support that:


Changing this to a pipe should solve your problem:

command = "amixer sget Master | awk -F'[][]' '/dB/ { print $2 }'"

Alternative you can start bash from within sh:

command = "bash -c 'amixer sget Master | awk -F'\\''[][]'\\'' '\\''/dB/ { print $2 }'\\'''"

But as you will soon realize, quoting and escaping will become a nightmare

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download