gpt4 book ai didi

python - Shell 命令从 python 失败,从 shell 确定

转载 作者:太空狗 更新时间:2023-10-29 11:09:17 24 4
gpt4 key购买 nike

我有一个 python 脚本,它根据给定的输入生成许多 shell 命令。问题是,当它尝试执行生成的命令时,它失败了,但是当我自己运行生成的命令时(即从命令行),它们执行成功。

这是生成的命令:

find /home/me/downloader/0-29/ -type f | grep -i .rpm$ | xargs -i cp {} /home/me/downloader/builds/0-29/

这是python脚本运行时的错误信息:

find: paths must precede expression: |Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

Could you help me understand what the problem is?

UPD: Here is the function i use for executing the generated commands:

def exec_command(command):
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
return output

最佳答案

由于您的命令是一个管道,您必须设置 shell=True 以便子进程将命令按原样发送到 shell:

command = 'find /home/me/downloader/0-29/ -type f | grep -i .rpm$ | xargs -i cp {} /home/me/downloader/builds/0-29/'
subprocess.call(command, shell=True)

或者,

process = subprocess.Popen(command, shell=True)
output = process.communicate()[0]
return output

此外,不要在带有管道的命令上在 python 中进行拆分。这将导致 find 作为其参数之一而不是作为 shell 运算符传递给 |

看来命令也可以简化:

command="find /home/me/downloader/0-29/ -type f -iname '*.rpm' -exec cp {} /home/me/downloader/builds/0-29/ \;"

由于上面不再是管道,只需稍作修改,它就可以拆分并提供给 shell=False 的子进程。修改是 '*.rpm' 周围的单引号用于保护 glob 免受 shell 扩展。使用 shell=False,shell 不会删除它们。所以,我们必须。对于 shell=False 和与 command.split() 一起使用:

command="find /home/me/downloader/0-29/ -type f -iname *.rpm -exec cp {} /home/me/downloader/builds/0-29/ \;"

关于python - Shell 命令从 python 失败,从 shell 确定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21672182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com