使用用户在Python中插入的文件运行Linux shell脚本

使用用户在Python中插入的文件运行Linux shell脚本,python,linux,input,ffmpeg,ffprobe,Python,Linux,Input,Ffmpeg,Ffprobe,我试图使用Python中用户输入文件预定义的命令来运行ffprobe命令。然后我将使用这个命令生成的文件在一个更有组织的视图中报告一些参数。我的代码是: import subprocess import json cmd = "ffprobe -v quiet -print_format -show_format -show_streams /path/to/input/file.mp4 > output.json" subprocess.call(cmd.split()) with

我试图使用Python中用户输入文件预定义的命令来运行ffprobe命令。然后我将使用这个命令生成的文件在一个更有组织的视图中报告一些参数。我的代码是:

import subprocess
import json

cmd = "ffprobe -v quiet -print_format -show_format -show_streams /path/to/input/file.mp4 > output.json" 
subprocess.call(cmd.split())

with open('output.json') as json_data:
        data = json.load(json_data)
        json_data.close()
        d = float((data["streams"][0]["duration"]))
        t = (data["streams"][0]["time_base"])
        fps = [float(x) for x in t.split('/')]
        print "==========================General=========================="
        print "Name of the File: %s" %(data["format"]["filename"])
        print "Duration: %.2f minutes" %(d/60)
        print "Frame Rate: %d fps" %fps[1]
        print "Bitrate: %.2f Mbps" %(float(data["format"]["bit_rate"])/1000000)
我想使用:
input\u file=(“请输入输入文件的路径:”)
然后在代码第二行的ffprobe命令中使用input\u文件。但我不确定如何在引用中做到这一点。还请注意,文件名还应包括类似input.mp4的扩展名

Shell重定向(
)仅在将
Shell=True
传递给
子流程调用()时才起作用。通常,您应该避免这样做,特别是当您将用户输入作为已执行命令的一部分时,在这种情况下,您需要确保正确转义用户输入,例如使用
shlex.qutoe()

不必在shell中使用重定向,您可以打开文件以用python编写并将其作为标准输出传递,或者如果不需要该文件,您可以使用
子进程。请选中output()
,而不是
子进程。call()

或与使用文件写入相同:

input_filename = raw_input("Please enter the path to your input file: ")
cmd = ['ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams',
       input_filename]

with open('output.json', 'wb') as outfile:
    subprocess.call(cmd, stdout=outfile)

with open('output.json', 'r') as infile:
    data = json.load(infile)

...
在这种情况下,不需要引用输入文件名,因为它不是由shell解释的。

这应该可以:

#!/usr/bin/env python
import subprocess
import json

input_file = raw_input("Please enter the input file path: ")

returned_data = subprocess.check_output(['ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams', input_file])
data = json.loads(returned_data.decode('utf-8'))

感谢您的提示,但您的两个建议似乎都返回了语法错误。“无效语法”您是将其复制到文件中还是将其粘贴到交互式解释器中?不应该有语法错误,但是当粘贴到解释器时,某些块需要由空的lline终止,并相应地重新格式化。此外,如果在
原始输入后粘贴下一行,则将使用
,可能会弄糟事情。此外,我还将
-print\u format
更改为
-print\u format json
,因为这可能是我的初衷。
#!/usr/bin/env python
import subprocess
import json

input_file = raw_input("Please enter the input file path: ")

returned_data = subprocess.check_output(['ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams', input_file])
data = json.loads(returned_data.decode('utf-8'))