I'm using subprocess.run to run a command that has a for loop in it but not getting back the expected result. Here's a simplified case that shows the issue.
In bash shell:
for i in {1..3}; do echo ${i}; done
The result is:
1
2
3
Which is what I expect and want. However in my code when I execute this following:
subprocess.run("for i in {1..3}; do echo ${i}; done", shell=True, check=True)
the result printed on my shell is {1..3}
But what I want the result to be is:
1
2
3
like when I execute the code in my shell. Would appreciate any insights on how to fix this, thanks!
I would recommend using subprocess.popen:
from subprocess import popen
process = subprocess.Popen("bash for i in {1..3}; do echo $i; done")
try:
outs, errs = process.communicate(timeout=15)
except TimeoutExpired as e:
process.kill()
outs, errs = process.communicate()
Or, using your original line of code:
subprocess.run("bash for i in {1..3}; do echo $i; done", shell=True, check=True, capture_output=True)
I was able to gleam this information from the subprocess doc's located here: Subprocess Pypi Docs
Regards, and I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With