如何在Python循环中执行命令行?
我正在尝试找出用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 个回答
你的代码想要做的事情是对一个文件执行一个命令,如果出现错误就退出脚本。subprocess.check_output
这个功能可以实现这个目的——如果子进程返回了一个错误代码,它就会抛出一个Python错误。根据你是否想要明确处理错误,你的代码可能会像这样:
file in fileList.split(";"):
...code to create command string...
subprocess.check_output(command, shell=True)
这段代码会执行命令,如果有错误的话,会打印出错误信息,或者
file in fileList.split(";"):
...code to create command string...
try:
subprocess.check_output(command,shell=True)
except subprocess.CalledProcessError:
...handle errors...
sys.exit(1)
这段代码会打印出错误代码并退出,就像你的脚本那样。
你可以考虑使用 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。
如果你只是想一个接一个地运行命令,那么放弃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
更新:提问者更新了问题,提供了样本数据,说明他是在Windows系统上。你可以通过cygwin或其他一些软件包在Windows上获取bash
,但如果你在Windows上,使用PowerShell可能更合适。不幸的是,我没有Windows电脑,但应该有类似的错误检查机制。这里有一个关于PowerShell错误处理的参考资料。
试试使用命令模块(这个模块在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这个情况的方式不对。