python - 运行 带单引号的子进程命令

python - run subprocess command with single quote

我想 运行 python 中的以下命令。它查找目录中文件的持续时间。但是我有一个语法错误,我不确定如何解决。

find /Volumes/Storage/test. -maxdepth 1 -iname '*.mp4' -exec ffprobe -v quiet -of csv=p=0 -show_entries format=duration {} \; | paste -sd+ -| bc    

Python代码:

import subprocess

cmd = "/Volumes/Storage/test. -maxdepth 1 -iname '*.mp4' -exec ffprobe -v quiet -of csv=p=0 -show_entries format=duration {} \; | paste -sd+ -| bc"
result2 = subprocess.run(['find', '/Volumes/Storage/test. -maxdepth 1 -iname '*.mkv' -exec ffprobe -v quiet -of csv=p=0 -show_entries format=duration {} \; | paste -sd+ -| bcmd'])
print (result2)

我收到这个错误:

 File "/Volumes/Storage/command2.py", line 4
    result2 = subprocess.run(['find', '/Volumes/Storage/test. -maxdepth 1 -iname '*.mp4' -exec ffprobe -v quiet -of csv=p=0 -show_entries format=duration {} \; | paste -sd+ -| bcmd'])
                                                                                   ^
SyntaxError: invalid syntax

我怀疑是单引号引起的。里面有单引号的subprocess怎么用?

谢谢

您可以转义引号

# escaped
'random string \'quote\' close string'

# not escaped
'random string 'quote' close string'

正如您已经从语法突出显示中看到的那样,作为命令一部分的单引号正在终止您也用单引号引起来的字符串。一个非常简单的解决方法是简单地为字符串使用双引号,即

result2 = subprocess.run(["find", "/Volumes/Storage/test. -maxdepth 1 -iname '*.mp4' -exec ffprobe -v quiet -of csv=p=0 -show_entries format=duration {} \; | paste -sd+ -| bcmd"])

另一种方法是用反斜杠转义引号 ' \' '(这是一个包含单引号的字符串)