在 Python 中使用`subprocess` 编写 bash for 循环的正确方法 [英] Correct way in Python to write a bash for loop with `subprocess`
问题描述
在另一个SO问题中,我看到了这个编写 for
循环时 bash
的语法在 Python 中似乎不起作用:
In this other SO question I saw that this syntax of bash
when writing a for
loop doesn't seem to work in Python:
~ $ for num in {2..4}; do echo $num; done
2
3
4
因为不是 4 次不同的迭代,它只执行一个:
As instead of 4 different iterations, it does a single one:
>>> print(subprocess.check_output("for num in {2..4}; do echo $num; done", shell=True).decode())
{2..4}
为什么 Python 不支持这种语法?
Why is it this syntax is not supported in Python?
我看到确实支持其他语法:
I see this other syntax is indeed supported:
>>> print(subprocess.check_output("for num in 2 3 4; do echo $num; done", shell=True).decode())
2
3
4
推荐答案
发布 How to use the bash shell with Python's subprocess module 而不是/bin/sh 表明它使用 /bin/sh
但你可以使用 executable='/bin/bash'
改变它
Post How to use the bash shell with Python's subprocess module instead of /bin/sh shows that it uses /bin/sh
but you can use executable='/bin/bash'
to change it
import subprocess
print(subprocess.check_output("for num in {2..4}; do echo $num; done", shell=True, executable='/bin/bash').decode())
<小时>
最终你可以使用 bash -c "command"
import subprocess
print(subprocess.check_output('bash -c "for num in {2..4}; do echo $num; done" ', shell=True).decode())
这篇关于在 Python 中使用`subprocess` 编写 bash for 循环的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!