Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run an inline shell script from python?

Tags:

python

bash

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.

like image 901
ThiefMaster Avatar asked Mar 05 '26 05:03

ThiefMaster


1 Answers

import subprocess

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

subprocess.call(['sh', '-c', script])
like image 129
nosklo Avatar answered Mar 07 '26 19:03

nosklo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!