有什么简单的方法可以运行复杂的/长的shell命令。我只需要命名空间。python对Awk并不满意。如何将输出存储在下面示例中的变量中,..or存储在文件中更好。?
p1 = subprocess.Popen('kubectl get ns ', shell=True, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2 = subprocess.Popen('grep mynamespace', shell=True, stdin=p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
p3 = subprocess.Popen('cut -d" " -f 1', shell=True, stdin=p2.stdout)
p1.stdout.close()
out, err = p3.communicate()
发布于 2022-07-23 00:53:53
您可以使用Kubernetes Python客户端来完成该任务:
# python -m pip install kubernetes
from kubernetes import client, config
# Load ~/.kube/config
config.load_kube_config()
c = client.CoreV1Api()
name_space_list = c.list_namespace()
for name_space in name_space_list.items:
print(name_space.metadata.name)
我经常避免尽可能多地使用子进程。
发布于 2022-07-23 01:04:36
尽管@PraysonWDaniel的答案可能是正确的--如果可以的话,可以使用库--没有理由不使用python中的文本操作--如果您要这样做的话:
from subprocess import run
def get_namespace():
p = run(["kubectl", "get", "ns"], capture_output=True, encoding="utf8")
ns = next(l for l in p.stdout.splitlines() if "mynamespace" in l)
return ns.split()[0]
https://stackoverflow.com/questions/73079000
复制