Shell命令从蟒蛇失败,壳牌确定 [英] Shell command fails from python, ok from shell

查看:166
本文介绍了Shell命令从蟒蛇失败,壳牌确定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生成一个数字从给定输入shell命令的python脚本。问题是,当它试图执行所生成的命令,它失败了,但是当我运行生成的命令自己(即在命令行),它们被成功执行。

I have a python script that generates a number of shell commands from the given input. The problem is that when it tries to execute the generated commands, it fails, but when i run the generated commands myself (that is, from the command line), they are executed successfully.

下面是生成的命令:

Here is the generated command:

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

下面是当它是由python脚本运行错误消息:

Here is the error message when it is run by the python script:

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 :这是我用来执行指令产生的功能:

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

推荐答案

由于您的命令是一个管道,你必须设置壳= TRUE ,这样子会发送命令,为的是,到shell:

Since your command is a pipeline, you must set shell=True so that subprocess will send the command, as is, to the 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

另外,不要做蟒蛇分裂与管道中的命令。这将导致找到传递 | 作为它的参数,而不是作为一个外壳经营者有一个

Also, do not do splitting in python on a command with a pipeline. This will result in find being passed | as one of its arguments instead of as a shell operator.

这似乎也该命令可以简化为:

It also appears that the command can be simplified:

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

由于上述已不再是一个管道,它可能与一小的修改,被分割并给予与壳到子过程=假。该修改是围绕'*。转单引号是为了保护从shell扩展水珠。与壳牌=假,外壳不会删除它们。所以,我们不得不这样做。壳=假,并为使用 command.split()

Since the above is no longer a pipeline, it could, with a minor modification, be split and given to subprocess with shell=False. The modification is that the single-quotes around '*.rpm' are there to protect the glob from shell expansion. With shell=False, the shell doesn't remove them. So, we have to. For shell=False and for use with command.split():

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

这篇关于Shell命令从蟒蛇失败,壳牌确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆