gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:20:53 25 4
gpt4 key购买 nike

我正在尝试使用 Python 中的用户输入文件预定义来运行 ffprobe 命令。然后我将使用此命令生成的文件以更有条理的 View 报告一些参数。我的代码是:

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_file = ("请输入您的输入文件的路径:"),然后在代码第二行的 ffprobe 命令中使用 input_file。但我不确定如何在引号内做到这一点。另请注意,文件名还应包含 input.mp4 等扩展名。

最佳答案

Shell 重定向 (>) 仅在将 shell=True 传递给 subprocess.call() 时才起作用。一般来说,您应该避免这样做,特别是如果您将用户输入作为执行命令的一部分,在这种情况下您需要确保用户输入被正确转义,例如通过使用shlex.qutoe()

您可以打开文件以在 python 中写入并将其作为 stdout 传递,而不是在 shell 中使用重定向,或者如果您不需要该文件,您可以使用 subprocess.check_output() 而不是 subprocess.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]

returned_data = subprocess.check_output(cmd)
data = json.loads(returned_data.decode('utf-8')) # assuming the returned data is utf-8 encoded

...

或者与使用文件写入相同:

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 不会解释它。

关于python - 使用用户在 Python 中插入的文件运行 Linux shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42063869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com