Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

bash - Passing input to an executable using Python subprocess module

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) and I want to automate this process using Python's subprocess module.

I tried doing this:

data=subprocess.Popen(['./a.out','< 0.in'],stdout=subprocess.PIPE,stdin=subprocess.PIPE).communicate()

Nothing was printed (data[0] was blank) when I ran this. What is the right method to do what I want to do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...