[英]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.