2

I'm working on a small project where I need to control a console player via python. This example command works perfectly on the Linux terminal:

mplayer -loop 0 -playlist <(find "/mnt/music/soundtrack" -type f | egrep -i '(\.mp3|\.wav|\.flac|\.ogg|\.avi|\.flv|\.mpeg|\.mpg)'| sort)

In Python I'm doing the following:

command = """mplayer -loop 0 -playlist <(find "/mnt/music/soundtrack" -type f | egrep -i '(\.mp3|\.wav|\.flac|\.ogg|\.avi|\.flv|\.mpeg|\.mpg)'| sort)""" 
os.system(command)

The problem is when I try it using Python it gives me an error when I run it:

sh: 1: Syntax error: "(" unexpected

I'm really confused here because it is the exact same string. Why doesn't the second method work?

Thanks.

3 Answers 3

3

Your default user shell is probably bash. Python's os.system command calls sh by default in linux.

A workaround is to use subprocess.check_call() and pass shell=True as an argument to tell subprocess to execute using your default user shell.

import subprocess
command = """mplayer -loop 0 -playlist <(find "/mnt/music/soundtrack" -type f | egrep -i '(\.mp3|\.wav|\.flac|\.ogg|\.avi|\.flv|\.mpeg|\.mpg)'| sort)"""
subprocess.check_call(command, shell=True)
Sign up to request clarification or add additional context in comments.

3 Comments

I tried what you suggested however a different error is occurring: /bin/sh: 1: Syntax error: "(" unexpected with a traceback ...returned non-zero exit status 2. Also tried this subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) but I get /bin/sh: 1: Syntax error: "(" unexpected. Tried a bunch of things and nothing seems to be working...
A non-zero exit normally indicates a command failed in Linux. I would check the mplayer documentation to find out what the error is (if any).
Ok, I'm sure I'll get this working soon enough. At least I now know why it isn't working. Thank you.
1

Your python call 'os.system' is probably just using a different shell than the one you're using on the terminal: os.system() execute command under which linux shell?

The shell you've spawned with os.system may not support parentheses for substitution.

2 Comments

He's using <(...) for process substitution, not grouping.
Thanks for the correction. I just learned something new. Here's an explanation for anyone else who wants it: en.wikipedia.org/wiki/Process_substitution
0
import subprocess  
 
COMND=subprocess.Popen('command',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
COMND_bytes = COMND.stdout.read() + COMND.stderr.read()  
print(COMND_bytes)

1 Comment

Please add some explanation. Right now it is unclear why this works while the original code doesn't

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.