简体   繁体   English

如何在Python中获取已执行命令的返回值

[英]How to get return value of a executed command in Python

I am trying to get the output of a shell command I try to execute using python but I get an error.我正在尝试获取我尝试使用python执行的shell command的输出,但出现错误。

How can I get the response/return value from executing a bash command如何从执行 bash 命令中获取响应/返回值

This is what I have done:这就是我所做的:

import subprocess
import time

# NAMESPACE = input("Namespace: ")

# # Create a namespace
# subprocess.call(["kubectl", "create", "namespace", NAMESPACE])

# build a docker image to deploy the application
DOCKER_OUTPUT = subprocess.call(["docker", "build", "-t", "banuka/node-web-app", "."])
print("Docker output is: " + DOCKER_OUTPUT)

Somehow this gives an error:不知何故,这给出了一个错误:

unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat /home/jananath/Desktop/python-script/Dockerfile: no such file or directory Traceback (most recent call last): File "/home/jananath/Desktop/python-script/bitesize-platform-troubleshooter/test/test.py", line 11, in print("Docker output is: " + DOCKER_OUTPUT) TypeError: can only concatenate str (not "int") to str无法准备上下文:无法评估 Dockerfile 路径中的符号链接:lstat /home/jananath/Desktop/python-script/Dockerfile:没有这样的文件或目录回溯(最近一次调用):文件“/home/jananath/Desktop/python -script/bitesize-platform-troubleshooter/test/test.py", line 11, in print("Docker output is: " + DOCKER_OUTPUT) TypeError: can only concatenate str (not "int") to str

Can someone please help me to print the response without getting this error (from python)?有人可以帮我打印响应而不会收到此错误(来自python)吗?

The result of system commands is usually an integer associated with an exit status.系统命令的结果通常是一个与退出状态相关的整数。 You can do print("Docker output is: " + str(DOCKER_OUTPUT)") To convert the int to a String, or you can use other Python string formatting options (depending on your Python version).您可以执行print("Docker output is: " + str(DOCKER_OUTPUT)")将 int 转换为 String,或者您可以使用其他 Python 字符串格式选项(取决于您的 Python 版本)。

Example: f-string print(f"Docker output is {DOCKER_OUTPUT}")示例:f-string print(f"Docker output is {DOCKER_OUTPUT}")

Example: .format() print("Docker output is {}".format(DOCKER_OUTPUT))示例:.format() print("Docker output is {}".format(DOCKER_OUTPUT))

If you want a more verbose output (ie not just the zero/nonzero exit status) you can do the following:如果您想要更详细的输出(即不仅仅是零/非零退出状态),您可以执行以下操作:

cmd = 'docker build -t banuka/node-web-app .'
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
output, err = p.communicate()
print('This is the output: {}, and this is the error: {}'.format(output, error))

You shouldn't use subprocess.call it's in the old deprecated API if you lookup the docs you can find this example.如果您查找可以找到此示例的文档,则不应使用 subprocess.call 它在旧的已弃用 API 中。

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')

The correct way of capturing the out put would be for example:例如,捕获输出的正确方法是:

out=subprocess.run(["ls", "-l","/foo/bar"], capture_output=True).stdout

Make sure you are running the latest version of python you are able to and the latest set of functions because they tend to be more convenient and easier to use.确保您运行的是最新版本的 Python 和最新的函数集,因为它们往往更方便、更易于使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM