3

I have a small shell script in a string inside my python file.
Now I'd like to run this script via subprocess.call() and I wonder what's the best way.

My first thought was to write the script to a StringIO and specify that via stdin=... but unfortunately you cannot specify a StringIO since it doesn't have a fileno() method.

Of course I could use stdin=subprocess.PIPE and then write to it using subprocess.communicate() but I wonder if there's a simpler method.

1 Answer 1

9
import subprocess

script = """
for x in 1 2 3 ; do echo $x ; sleep 1 ; done
"""

subprocess.call(['sh', '-c', script])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that solved my problem. I tried that before but apparently I failed at copy&paste and thus my bash script had an error.
for the record, subprocess.Popen(['sh'], stdin=subprocess.PIPE).communicate(script) would also work, but you lose stdin.

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.