簡體   English   中英

如何在 python 循環中執行命令行?

[英]How to execute command line in a python loop?

我正在嘗試確定使用 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

嘗試使用 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)

您對要解決的問題並不完全清楚。 如果我不得不猜測為什么您的命令在循環中失敗,那可能是您處理 console=False 情況的方式。

如果您只是一個接一個地運行命令,那么最簡單的方法可能是拋棄 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 錯誤處理的參考

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

您的代碼試圖完成的是對文件運行命令,並在出現錯誤時退出腳本。 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 錯誤代碼並退出,就像在您的腳本中一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM