通过Python运行终端命令的问题

2024-06-16 13:08:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个小项目,我需要通过python控制控制台播放器。这个示例命令在Linux终端上运行得非常好:

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

在Python中,我执行以下操作:

^{pr2}$

问题是,当我使用Python进行尝试时,当我运行它时会出现一个错误:

sh: 1: Syntax error: "(" unexpected

我真的很困惑,因为它是完全相同的字符串。为什么第二种方法不起作用?在

谢谢。在


Tags: 项目命令loop终端示例linuxtypemusic
2条回答

您的默认用户shell可能是bash。默认情况下,在linux中,Python的os.system命令调用sh。在

解决方法是使用subprocess.check_call()并传递^{}作为参数,告诉{}使用默认用户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)

你的python调用'操作系统'可能只是使用了与您在终端上使用的外壳不同的外壳: os.system() execute command under which linux shell?

你生出的壳操作系统不支持括号替换。在

相关问题 更多 >