路径字符串中的子流程空间

时间:2018-06-26 21:45:11

标签: python python-3.x subprocess

我遇到一个奇怪的情况,我有一个方法在同一方法中从路径两次调用ffmpeg可执行文件-第一次起作用,但是第二次却不起作用,我也无法弄清为什么。

ffmpeg可执行文件位于路径

c:\GUI\My app\ffprobe.exe

我用代码称呼它

for n in (self.file_numbers):
    master_file = n + '.mxf' # eg C31_9213.mxf

    # Get Metadata 1st time (WORKS)
    self.mastermeta = self.getMetadata(master_file) 

    # Get metadata for connected parts (DOESNT WORK)
    self.parts_meta = []
    if master_file: # read parts from a sidecar file...
        with open(sidecar, 'r') as sc:
            # sidecar file contains paths - should split '/' lines into list 
            linelist = [line.strip() for line in sc]
            self.parts_from_file = [p.split('/') for p in linelist]

            # OPTION Check parts & get metadata list for parts 
            if self.parts_from_file: 
                for p in self.parts_from_file:
                    part = str(p[-1]) # the last index is a filename C63_4526.mxf
                    print(part, type(part)) # prints filename and type string identical to above example.
                    partmeta = self.getMetadata(part)
                    self.parts_meta.append(partmeta)

和getMetadata函数(在我第一次调用它时起作用)看起来像这样...

    def getMetadata(self, master_file=None):
        root = "{}/ffprobe.exe".format(self.program_root.replace('\\', '/')) # /path/to/exe

        cmd = "{} -v quiet -print_format json -show_streams -show_format -sexagesimal".format(root)
        args = shlex.split(cmd)
        args.append(master_file) 

        # GETS META FOR MASTER FILES::::
        # run the ffprobe process, decode stdout into utf-8 & convert to JSON
        ffprobeOutput = subprocess.check_output(args).decode('utf-8')
        ffprobeOutput = json.loads(ffprobeOutput)
        ... more ...
        <returns a list>

我没有将可执行文件从 C:\ My App \ ffprobe.exe 中移出,也没有更改 self.program_root ,并且如果我将对第二个调用的注释掉, getMetadata函数可以正常工作。

路径中的空格第一次不会引起问题,但是第二次出现错误,同一路径突然被shlex.split拆分为文件夹名称中空格的两个部分...

*Traceback (most recent call last):
   File "GUI_5.py", line 450, in <module>
   gui = Main()
   File "GUI_5.py", line 238, in __init__
   self.setupUi(self)
   File "GUI_5.py", line 155, in setupUi
   self.openFolderDialog()
   File "GUI_5.py", line 428, in openFolderDialog
   partmeta = self.getMetadata(part)
   File "GUI_5.py", line 292, in getMetadata
   ffprobeOutput = subprocess.check_output(args).decode('utf-8')
   File "c:\python35\Lib\subprocess.py", line 626, in check_output
   **kwargs).stdout
   File "c:\python35\Lib\subprocess.py", line 708, in run
   output=stdout, stderr=stderr)
   subprocess.CalledProcessError: Command '['C:/GUI/My', 'app/ffprobe.exe', '-v', 'quiet', '-print_format', 'json', '-show_streams', '-show
   _format', '-sexagesimal', "C45_0031.mxf'"]' returned non-zero exit status 1*

有人知道为什么会发生这种情况吗?

1 个答案:

答案 0 :(得分:0)

不管它为什么第一次起作用,如果其路径名包含空格,则应始终引用命令。将分配给cmd的行更改为:

cmd = '"{}" -v quiet -print_format json -show_streams -show_format -sexagesimal'.format(root)