Python Popen sending to process on stdin, receiving on stdout

前端 未结 1 1315
暖寄归人
暖寄归人 2021-02-20 11:22

I pass an executable on the command-line to my python script. I do some calculations and then I\'d like to send the result of these calculations on STDIN to the executable. When

相关标签:
1条回答
  • 2021-02-20 11:33

    A working example

    #!/usr/bin/env python
    import subprocess
    text = 'hello'
    proc = subprocess.Popen(
        'md5sum',stdout=subprocess.PIPE,
        stdin=subprocess.PIPE)
    proc.stdin.write(text)
    proc.stdin.close()
    result = proc.stdout.read()
    print result
    proc.wait()
    

    to get the same thing as “execuable < params.file > output.file”, do this:

    #!/usr/bin/env python
    import subprocess
    infile,outfile = 'params.file','output.file'
    with open(outfile,'w') as ouf:
        with open(infile,'r') as inf:
            proc = subprocess.Popen(
                'md5sum',stdout=ouf,stdin=inf)
            proc.wait()
    
    0 讨论(0)
提交回复
热议问题