需要使用 python 从以下代码的 cmd 命令获取 return 代码

Need to get return code from cmd command of the below code using python

这是我想要在 cmd 中使用 python 运行 的代码,我希望它成为 return 我在程序中相应处理的数据

SCHTASKS /query /TN TaskName >NUL 2>&1

如您所见,如果找不到 TaskName,此代码可能 return 是一个错误值。

我想获取此数据,即:如果任务确实存在,我需要取回一些错误代码,并且需要在它确实存在时获取不同的 return 代码。

我尝试使用

var=subprocess.Popen(["start", "cmd", "/k", "SCHTASKS /query /TN TaskName >NUL 2>&1"], shell = True)
print var

但这大概只是给了我一些对象在内存中的位置。由于这是使用 cmd 的帮助,因此 returning 似乎需要不同的语法。

不要使用 start 在后台启动,因为您将无法获得 return 代码或输出。

如果您只想要命令的 return 代码并隐藏 output/error 消息,只需创建一个 Popen 对象然后等待任务完成:

p = subprocess.Popen(["SCHTASKS","/query","/TN","TaskName"],stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return_code = p.wait()

Python 2没有DEVNULL,所以你必须手动打开一个空流(How to hide output of subprocess in Python 2.7):

with open(os.devnull, 'w')  as FNULL:
    p = subprocess.Popen(["SCHTASKS","/query","/TN","TaskName"],stdout=FNULL, stderr=FNULL)
    return_code = p.wait()

如果您需要在后台执行此操作,请将上述代码包装在 python 线程中。另外:

  • 始终将命令行参数作为列表传递,以便自动处理引号(如果需要)
  • 不要使用 start,因为您会失去对流程及其 return 代码的控制。
  • 不要使用 shell=True,因为使用 Popen 重定向到 DEVNULL 更便于携带。