通过Python运行终端命令时出现问题 [英] Problems running terminal command via Python

查看:73
本文介绍了通过Python运行终端命令时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小项目,需要通过python控制控制台播放器.此示例命令可在Linux终端上完美运行:

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)

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

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)

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

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?

谢谢.

推荐答案

您的默认用户shell可能是 bash .在Linux中,Python的 os.system 命令默认调用 sh .

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

一种解决方法是使用 subprocess.check_call()并传递 shell = True 作为参数,告诉 subprocess 使用默认用户shell执行.

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)

这篇关于通过Python运行终端命令时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆