Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use for loop in Subprocess.run command [duplicate]

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!

like image 707
Justin Owusu Avatar asked Mar 27 '26 03:03

Justin Owusu


1 Answers

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.

like image 52
billy Avatar answered Mar 29 '26 17:03

billy