5

I have a python script in which I need to invoke a shell command. The shell command can accept its input from either a file or stdin.

In my script, the input is stored in a variable. What is the proper way to invoke the command? If it matters, the shell command produces no output.

I know I could write the variable's content into a file and invoke the command with the file as argument but that seems inelegant. Surely, there's a better way.

Can someone tell me what it is? Thanks.

4

2 Answers 2

5

You can use the subprocess module.

import subprocess
process = subprocess.Popen(["Mycommand", "with", "arguments"], stdin=subprocess.PIPE)
process.communicate("My text")
Sign up to request clarification or add additional context in comments.

4 Comments

"Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process." (From docs.python.org/2/library/subprocess.html)
@palvarez89 Good call. I fixed it.
communicate() is a one-off method. To do that repeatedly, I copied some code from its implementation that handled stdin in a separate thread.
@ivan_pozdeev My answer did use process.stdin.write, but as palvarez89 mentioned, that is not the preferred way. The OP mentioned trying to write the variable's content into a file and invoke the command with the file as argument. If it were a problem to use a one-off method, that would not have been suggested.
0

Refer to How do I pass a string into subprocess.Popen (using the stdin argument)?

For python 3.5+ (3.6+ for encoding), you can use input:

from subprocess import check_output   
output = check_output(["cat","-b"],
        input="-foo\n-bar\n-foobar", encoding='ascii')
print(output)

example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.