简体   繁体   中英

Problems running terminal command via Python

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.

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)

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM