[英]How to execute command line in a python loop?
I am trying to determine the best way to execute something in command line using python.我正在尝试确定使用 python 在命令行中执行某些操作的最佳方法。 I have accomplished this with subprocess.Popen() on individual files.
我已经在单个文件上使用subprocess.Popen()完成了这一点。 However, I am trying to determine the best way to do this many time with numerous different files.
但是,我正在尝试确定使用许多不同文件多次执行此操作的最佳方法。 I am not sure if I should create a batch file and then execute that in command, or if I am simply missing something in my code.
我不确定我是否应该创建一个批处理文件然后在命令中执行它,或者我是否只是在我的代码中遗漏了一些东西。 Novice coder here so I apologize in advance.
新手编码员在这里,所以我提前道歉。 The script below returns a returncode of 1 when I use a loop, but a 0 when not in a loop.
下面的脚本在我使用循环时返回返回码 1,但在不在循环中时返回 0。 What is the best approach for the task at hand?
手头任务的最佳方法是什么?
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: An example command string looks like this:编辑:示例命令字符串如下所示:
C:\Path\to\executable.exe -i C:\path\to\input.ext -o C:\path\to\output.ext C:\Path\to\executable.exe -i C:\path\to\input.ext -o C:\path\to\output.ext
Try using the commands module (only available before python 3)尝试使用 commands 模块(仅在 python 3 之前可用)
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
Your code might look like this您的代码可能如下所示
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)
You are not entirely clear about the problem you are trying to solve.您对要解决的问题并不完全清楚。 If I had to guess why your command is failing in the loop, its probably the way you handle the console=False case.
如果我不得不猜测为什么您的命令在循环中失败,那可能是您处理 console=False 情况的方式。
If you are merely running commands one after another, then it is probably easiest to cast aside Python and stick your commands into a bash script.如果您只是一个接一个地运行命令,那么最简单的方法可能是抛弃 Python 并将您的命令粘贴到 bash 脚本中。 I assume you merely want to check errors and abort if one of the commands fails.
我假设您只想检查错误并在其中一个命令失败时中止。
#!/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
Update : OP updated his question with sample data that indicate he is on Windows.更新:OP 用表明他在 Windows 上的示例数据更新了他的问题。 You can get
bash
for Windows through cygwin or various other packages, but it may make more sense to use PowerShell if you are on Windows.您可以通过cygwin或各种其他软件包获得适用于 Windows 的
bash
,但如果您使用的是 Windows,则使用 PowerShell 可能更有意义。 Unfortunately, I do not have a Windows box, but there should be a similar mechanism for error checking.不幸的是,我没有 Windows 盒子,但应该有类似的错误检查机制。 Here is a reference for PowerShell error handling.
这是 PowerShell 错误处理的参考。
You might consider using subprocess.call您可以考虑使用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)
It also will output 0 for success and 1 for failure.它还将输出 0 表示成功,1 表示失败。
What your code is trying to accomplish is to run a command on a file, and exit the script if there's an error.您的代码试图完成的是对文件运行命令,并在出现错误时退出脚本。
subprocess.check_output
accomplishes this - if the subprocess exits with an error code it raises a Python error. subprocess.check_output
完成了这个 - 如果子进程以错误代码退出,它会引发 Python 错误。 Depending on whether you want to explicitly handle errors, your code would look something like this:根据您是否要显式处理错误,您的代码将如下所示:
file in fileList.split(";"):
...code to create command string...
subprocess.check_output(command, shell=True)
Which will execute the command and print the shell error message if there is one, or如果有,它将执行命令并打印 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)
Which will print the shell error code and exit, as in your script.这将打印 shell 错误代码并退出,就像在您的脚本中一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.