首页 > 解决方案 > 如何将json内容传递给python子进程或json文件

问题描述

我正在使用 python subprocess.popen 运行 openshift 命令。

我的 subprocess.popen 看起来像:

subprocess.Popen(['oc','create','-n',project,'-f','resource.json'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)

我正在尝试像这样传递 json 文件。但这不是我要创建的资源。有谁知道我可以将json内容传递给它的任何其他方式。

标签: pythonjsonlinuxsubprocessopenshift

解决方案


由于 OpenShift 是 Kubernetes,如果您想使用 Python Kubernetes 客户端与 OpenShift 交互,可能值得一试:https ://github.com/kubernetes-client/python

您的代码使用subprocess看起来正确,因此请检查打印的内容stdoutstderr

import subprocess

project = 'simon'
process = subprocess.Popen(['oc','create','-n',project,'-f','resource.json'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)

for line in process.stderr:
    print(line.strip())

for line in process.stdout:
    print(line.strip())

例如:

$ python3 test.py
b'pod/test created'
$ python3 test.py
b'Error from server (AlreadyExists): error when creating "resource.json": pods "test" already exists'

推荐阅读