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

rqqzpn5f  于 2022-11-18  发布在  Windows
关注(0)|答案(4)|浏览(129)

我正在尝试使用python确定在命令行中执行某个东西的最佳方式。我已经在单个文件上使用subprocess.Popen()完成了这一点。然而,我正在尝试使用大量不同的文件多次确定执行此操作的最佳方式。我不确定是否应该创建一个批处理文件,然后在命令中执行该文件。或者我只是在我的代码中遗漏了一些东西。新手在这里,所以我提前道歉。下面的脚本返回一个returncode 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()

EDIT:示例命令字符串如下所示:
C:\路径\到\可执行文件. exe-i C:\路径\到\输入. ext-o C:\路径\到\输出. ext

djmepvbi

djmepvbi1#

尝试使用commands模块(仅在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)

你并不完全清楚你要解决的问题。如果我必须猜测为什么你的命令在循环中失败,那可能是你处理控制台=假的方式。

ttygqcqt

ttygqcqt2#

如果您只是一个接一个地运行命令,那么最简单的方法可能是抛开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或其他各种软件包获得bash for Windows,但如果你使用的是Windows,使用PowerShell可能会更有意义。不幸的是,我没有Windows框,但应该有类似的错误检查机制。下面是一个reference for PowerShell错误处理。

6l7fqoea

6l7fqoea3#

您可以考虑使用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表示失败。

r7knjye2

r7knjye24#

你的代码试图完成的是在一个文件上运行一个命令,并在出现错误时退出脚本。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错误代码并退出,就像在您的脚本中一样。

相关问题