3

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!

Kevin
  • 16,549
  • 8
  • 60
  • 74
Justin Owusu
  • 31
  • 1
  • 2

3 Answers3

1

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.

billy
  • 27
  • 8
0

You would want to spawn a subshell:

subprocess.run("sh -c 'for i in {1..3}; do echo ${i}; done'", shell=True, check=True)
l'L'l
  • 44,951
  • 10
  • 95
  • 146
0

In case of python3:

import subprocess
result = subprocess.getoutput("""for i in {1..3}; do echo ${i}; done""")
print(result)
ashish14
  • 650
  • 1
  • 8
  • 20