在Python中运行bash while循环

在Python中运行bash while循环,python,bash,python-3.x,while-loop,subprocess,Python,Bash,Python 3.x,While Loop,Subprocess,我试图在Python3.6脚本中运行bashwhile循环。到目前为止,我尝试的是: subprocess.run(args=['while [ <condition> ]; do <command> done;']) subprocess.run(args=['while[];do done;'])) 我得到以下错误: FileNotFoundError:[Errno 2]没有这样的文件或目录 有没有办法在Python中运行这样一个while循环?让您大吃一惊的部分

我试图在
Python3.6
脚本中运行
bash
while循环。到目前为止,我尝试的是:

subprocess.run(args=['while [ <condition> ]; do <command> done;'])
subprocess.run(args=['while[];do done;']))
我得到以下错误:

FileNotFoundError:[Errno 2]没有这样的文件或目录


有没有办法在
Python
中运行这样一个while循环?

让您大吃一惊的部分是以列表的形式提供参数。从:

如果popen2函数的cmd参数是字符串,则通过/bin/sh执行命令。如果是列表,则直接执行命令

这似乎是你想要的:

subprocess.run('i=0; while [ $i -lt 3 ]; do i=`expr $i + 1`; echo $i; done', shell=True)

请注意,它被指定为字符串而不是列表。

python3.x
中运行bash
for循环
与在
循环时运行
非常相似

#! /bin/bash

for i in */;
do
    zip -r "${i%/}.zip" "$i";
done
这将迭代一个路径并压缩所有目录。要在Python中运行bash脚本,请执行以下操作:

import subprocess

subprocess.run('for i in */;  do zip -r "${i%/}.zip" "$i"; done', shell=True)

欢迎来到SO:请认真阅读。向我们显示我们可以帮助您的代码。这缺少关键字参数。按原样,您正在尝试执行一个名为传入字符串“”的二进制文件。请注意,我从未见过有任何需要。
虽然
不是程序,但它是bash内置命令。尝试
bash-c“而…”
Thanx@dhke有效。您应该传递的参数是
['/bin/bash','-c','..您的代码..]
。这样,如果需要,您可以控制stdout和stderr。