How do I redirect stdout to a file when using subprocess.call in python?

后端 未结 2 1865
醉酒成梦
醉酒成梦 2020-12-01 14:53

I\'m calling a python script (B) from another python script (A).

Using subprocess.call, how do I redirect the stdout of B to a file that specify?

I\'m using

相关标签:
2条回答
  • 2020-12-01 15:24

    Pass a file as the stdout parameter to subprocess.call:

    with open('out-file.txt', 'w') as f:
        subprocess.call(['program'], stdout=f)
    
    0 讨论(0)
  • 2020-12-01 15:33

    Alternate approach

    import subprocess
    p=subprocess.Popen('lsblk -l|tee a.txt',stdout=subprocess.PIPE,shell=True)
    (output,err)=p.communicate()
    p_status=p.wait()
    print output
    

    Above code will write output of command to file a.txt

    0 讨论(0)
提交回复
热议问题