如何在python循环中执行命令行?

时间:2014-04-21 21:33:35

标签: python windows loops python-2.7 popen

我正在尝试使用python确定在命令行中执行某些操作的最佳方法。我已经使用subprocess.Popen()对单个文件完成了此操作。但是,我试图用很多不同的文件来确定这么多次的最佳方法。我不确定是否应该创建一个批处理文件,然后在命令中执行该文件,或者如果我只是在代码中遗漏了某些内容。新手编码器在这里,所以我提前道歉。当我使用循环时,下面的脚本返回1的返回码,但是当不在循环中时返回0。手头任务的最佳方法是什么?

def check_output(command, console):
    if console == True:
        process = subprocess.Popen(command)
    else:
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
    output, error = process.communicate()
    returncode = process.poll()
    return returncode, output, error

for file in fileList.split(";"):
    ...code to create command string...
    returncode, output, error = check_output(command, False)
    if returncode != 0:
        print("Process failed")
        sys.exit()

编辑:示例命令字符串如下所示:

C:\ Path \ to \ executable.exe -i C:\ path \ to \ input.ext -o C:\ path \ to \ output.ext

4 个答案:

答案 0 :(得分:0)

尝试使用命令模块(仅在python 3之前可用)

>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')

您的代码可能如下所示

import commands

def runCommand( command ):
    ret,output = commands.getstatutoutput( command )
    if ret != 0:
        sys.stderr.writelines( "Error: "+output )
    return ret

for file in fileList.split(';'):
    commandStr = ""
    # Create command string
    if runCommand( commandStr ):
        print("Command '%s' failed" % commandStr)
        sys.exit(1)

您并不完全清楚您要解决的问题。如果我不得不猜测为什么你的命令在循环中失败了,它可能就像你处理console = False一样。

答案 1 :(得分:0)

如果你只是一个接一个地运行命令,那么抛弃Python并将命令粘贴到bash脚本中可能是最容易的。我假设您只想检查错误并在其中一个命令失败时中止。

#!/bin/bash

function abortOnError(){
    "$@"
    if [ $? -ne 0 ]; then
        echo "The command $1 failed with error code $?"
        exit 1
    fi
}

abortOnError ls /randomstringthatdoesnotexist
echo "Hello World" # This will never print, because we aborted

更新:OP使用表明他在Windows上的示例数据更新了他的问题。 您可以通过cygwin或其他各种软件包获取Windows bash,但如果您使用的是Windows,则使用PowerShell可能更有意义。不幸的是,我没有Windows机器,但应该有类似的错误检查机制。这是PowerShell错误处理的reference

答案 2 :(得分:0)

您可以考虑使用subprocess.call

from subprocess import call

for file_name in file_list:
    call_args = 'command ' + file_name
    call_args = call_args.split() # because call takes a list of strings 
    call(call_args)

它也会输出0表示成功,1表示失败。

答案 3 :(得分:0)

您的代码尝试完成的是对文件运行命令,如果出现错误则退出脚本。 subprocess.check_output完成此操作 - 如果子进程以错误代码退出,则会引发Python错误。根据您是否要显式处理错误,您的代码将如下所示:

file in fileList.split(";"):
    ...code to create command string...
    subprocess.check_output(command, shell=True)

执行命令并打印shell错误消息(如果有)或

file in fileList.split(";"):
    ...code to create command string...
    try:
        subprocess.check_output(command,shell=True)
    except subprocess.CalledProcessError:
        ...handle errors...
        sys.exit(1)

将打印shell错误代码并退出,如脚本中所示。