sh到py的转换

2024-09-30 20:21:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在将一个shell脚本转换成python,但遇到了一个问题。当前脚本使用上一次运行命令的结果,如下所示。在

if [ $? -eq 0 ];
then
    testPassed=$TRUE
else
    testPassed=$FALSE
fi

我把if语句转换了,只是不确定$?部分。由于我是python的新手,我想知道是否有类似的方法可以做到这一点?在


Tags: 方法命令脚本falsetrueif语句shell
2条回答

您应该查看subprocess模块。有一个^{}方法用于查找退出代码(这是一种方法,还有其他方法)。如手册所述:

Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute

例如:

import subprocess

command=["ls", "-l"]

try:
  exit_code=subprocess.check_call(command)
  # Do something for successful execution here
  print("Program run")
except subprocess.CalledProcessError as e:
  print "Program exited with exit code", e.returncode
  # Do something for error here

这还将包括输出,您可以重定向到某个文件或按如下方式取消:

^{pr2}$

下面是一个使用非零退出代码的调用示例:

import subprocess
import os

command=["grep", "mystring", "/home/cwgem/testdir/test.txt"]

try:
  exit_code=subprocess.check_call(command, stdout=open(os.devnull, "w"))
  # Do something for successful execution here
  print("Program run")
except subprocess.CalledProcessError as e:
  print "Program exited with exit code", e.returncode
  # Do something for error here

输出:

$ python process_exitcode_test.py
Program exited with exit code 1

它被捕获为一个异常,您可以按照上面的方法处理。请注意,这不会处理诸如拒绝访问或找不到文件等异常。你需要自己处理。在

您可能需要使用sh module。它使Python中的shell脚本编写更加令人愉快:

import sh
try:
    output = sh.ls('/some/nen-existant/folder')
    testPassed = True
except ErrorReturnCode:
    testPassed = False

相关问题 更多 >