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

问题描述 投票:0回答:4

我正在尝试确定使用 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:\路径 o xecutable.exe -i C:\路径 o\input.ext -o C:\路径 o\output.ext

python windows loops python-2.7 popen
4个回答
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 情况的方式。


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 错误处理的参考


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 表示失败。


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 错误代码并退出,如您的脚本中所示。

© www.soinside.com 2019 - 2024. All rights reserved.