【问题标题】:How to get return value of a executed command in Python如何在 Python 中获取已执行命令的返回值
【发布时间】:2019-11-27 03:19:18
【问题描述】:

我正在尝试获取 shell command 的输出,我尝试使用 python 执行,但出现错误。

如何通过执行 bash 命令获取响应/返回值

这就是我所做的:

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)

不知何故,这给出了一个错误:

无法准备上下文:无法评估 Dockerfile 路径中的符号链接:lstat /home/jananath/Desktop/python-script/Dockerfile:没有这样的文件或目录 回溯(最近一次通话最后): 文件“/home/jananath/Desktop/python-script/bitesize-platform-troubleshooter/test/test.py”,第 11 行,在 print("Docker 输出为:" + DOCKER_OUTPUT) TypeError:只能将str(不是“int”)连接到str

有人可以帮我打印响应而不收到此错误(来自 python)吗?

【问题讨论】:

  • dockerfile和你的python脚本在同一个目录吗?
  • 是的。当我在 Dockerfile 所在的同一目录中的普通 shell 中运行命令时,命令执行没有任何错误,是的,python 文件也在同一目录中。

标签: python


【解决方案1】:

系统命令的结果通常是一个与退出状态相关的整数。您可以通过print("Docker output is: " + str(DOCKER_OUTPUT)") 将 int 转换为 String,或者您可以使用其他 Python 字符串格式化选项(取决于您的 Python 版本)。

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

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

【讨论】:

    【解决方案2】:

    如果您想要更详细的输出(即不仅仅是零/非零退出状态),您可以执行以下操作:

    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))
    

    【讨论】:

      【解决方案3】:

      您不应该使用 subprocess.call 它在旧的已弃用 API 中 如果你查找docs,你可以找到这个例子。

      >>> 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'')
      

      捕获输出的正确方法是:

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

      确保您正在运行最新版本的 python 和最新的函数集,因为它们往往更方便且更易于使用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-29
        • 2022-08-20
        • 1970-01-01
        • 2011-12-10
        • 2016-04-12
        • 2021-01-28
        相关资源
        最近更新 更多