首页 文章

Python:如何使用子进程重定向输出?

提问于
浏览
78

我在命令行中做了什么:

cat file1 file2 file3 > myfile

我想用python做什么:

import subprocess, shlex
my_cmd = 'cat file1 file2 file3 > myfile'
args = shlex.split(my_cmd)
subprocess.call(args) # spits the output in the window i call my python program

5 回答

  • 206
    size = 'ffprobe -v error -show_entries format=size -of default=noprint_wrappers=1:nokey=1 dump.mp4 > file'
    proc = subprocess.Popen(shlex.split(size), shell=True)
    time.sleep(1)
    proc.terminate() #proc.kill() modify it by a suggestion
    size = ""
    with open('file', 'r') as infile:
        for line in infile.readlines():
            size += line.strip()
    
    print(size)
    os.remove('file')
    

    当你使用 subprocess 时,必须杀死进程 . 这是一个例子 . 如果你不杀死进程, file 将为空,你什么都不读 . 它可以在 Windows 上运行 . 我不能确保它可以在Unix上运行 .

  • 0

    要回答原始问题,要重定向输出,只需将 stdout 参数的打开文件句柄传递给 subprocess.call

    # Use a list of args instead of a string
    input_files = ['file1', 'file2', 'file3']
    my_cmd = ['cat'] + input_files
    with open('myfile', "w") as outfile:
        subprocess.call(my_cmd, stdout=outfile)
    

    但正如其他人所指出的那样,为此目的使用像 cat 这样的外部命令是完全无关紧要的 .

  • 0

    一个有趣的案例是通过向其添加类似文件来更新文件 . 然后,不必在此过程中创建新文件 . 在需要附加大文件的情况下,它特别有用 . 这是直接从python使用teminal命令行的一种可能性 .

    import subprocess32 as sub
    
    with open("A.csv","a") as f:
        f.flush()
        sub.Popen(["cat","temp.csv"],stdout=f)
    
  • 4

    @PoltoS我想加入一些文件,然后处理生成的文件 . 我认为使用猫是最简单的选择 . 有更好的/ pythonic方式吗?

    当然:

    with open('myfile', 'w') as outfile:
        for infilename in ['file1', 'file2', 'file3']:
            with open(infilename) as infile:
                outfile.write(infile.read())
    
  • 21

    更新:不鼓励使用os.system,尽管仍然可以在Python 3中使用 .


    使用 os.system

    os.system(my_cmd)
    

    如果你真的想使用子进程,这里的解决方案(主要取自子进程的文档):

    p = subprocess.Popen(my_cmd, shell=True)
    os.waitpid(p.pid, 0)
    

    OTOH,你可以完全避免系统调用:

    import shutil
    
    with open('myfile', 'w') as outfile:
        for infile in ('file1', 'file2', 'file3'):
            shutil.copyfileobj(open(infile), outfile)
    

相关问题