Passing input to an executable using Python subprocess module

前端 未结 1 1374
长情又很酷
长情又很酷 2020-12-21 21:54

I have an input file called 0.in. To get the output I do ./a.out < 0.in in the Bash Shell.

Now, I have several such files (more than 500

相关标签:
1条回答
  • 2020-12-21 22:52

    Redirection using < is a shell feature, not a python feature.

    There are two choices:

    1. Use shell=True and let the shell handle redirection:

      data = subprocess.Popen(['./a.out < 0.in'], stdout=subprocess.PIPE, shell=True).communicate()
      
    2. Let python handle redirection:

      with open('0.in') as f:
          data = subprocess.Popen(['./a.out'], stdout=subprocess.PIPE, stdin=f).communicate()
      

    The second option is usually preferred because it avoids the vagaries of the shell.

    If you want to capture stderr in data, then add stderr=subprocess.PIPE to the Popen command. Otherwise, stderr will appear on the terminal or wherever python's error messages are being sent.

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