【发布时间】:2018-07-27 10:55:10
【问题描述】:
我有一个简单的脚本来了解如何在子进程调用中运行 shell for 循环。我在虚拟环境和 BASH shell 中从 GNU/Linux 运行它。
脚本:
from subprocess import call
shellCommand = ['for','c','in','$(seq 1 10)','do','echo','$c','done']
call(shellCommand, shell=True)
还有错误信息:
c: 1: c: Syntax error: Bad for loop variable
我在这里做错了什么?
【问题讨论】:
-
这不是有效的 shell 语法,不。这不是真正的 Python 问题,直接从 shell 运行相同的命令会失败。
-
对于 shell 命令,只需传入单个字符串,而不是列表:
shell_command = 'for c in $(seq 1 10); do echo $c; done', thencall(shell_command, shell=True)`。注意我添加的分号。
标签: python shell subprocess