【问题标题】:Run bash while loop in Python在 Python 中运行 bash while 循环
【发布时间】:2018-02-01 11:09:28
【问题描述】:

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

subprocess.run(args=['while [ <condition> ]; do <command> done;'])

我收到以下错误:

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

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

【问题讨论】:

  • 欢迎来到 SO:请使用 tour 并注意阅读 minimal reproducible example。向我们展示您的代码,我们可以帮助您。
  • 这缺少 shell=True 关键字参数。照原样,您正在尝试使用传入的字符串的名称执行二进制文件。请注意,我从未见过有任何需要。
  • while 不是程序,它是 bash 内置命令。试试bash -c "while ..."
  • 感谢@dhke 的成功。
  • 你应该传递的参数是['/bin/bash', '-c', ' .. your code ..']。这样,您可以根据需要控制 stdout 和 stderr。

标签: python bash python-3.x while-loop subprocess


【解决方案1】:

让您感到困惑的部分是将 args 作为列表提供。来自documentation

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

这似乎是你想要的:

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

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

【讨论】:

    【解决方案2】:

    Python 3.x 中运行 bash for loop 非常类似于运行 while 循环。

    #! /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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2020-04-29
      • 2016-09-07
      • 1970-01-01
      • 2011-06-10
      相关资源
      最近更新 更多