【发布时间】:2020-03-25 00:16:19
【问题描述】:
我正在尝试使用 python 执行这个 shell 命令
但问题是,即使有错,它也不给出输出:
这是我尝试过的:
get_ns_p1 = subprocess.Popen(['kubectl', 'get', 'ns'], stdout=subprocess.PIPE)
get_ns_p2 = subprocess.Popen(["grep", "-E", "\'(^|\s)"+NAMESPACE+"($|\s)\'"], stdin=get_ns_p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
get_ns_p1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits.
out_ns, err = get_ns_p2.communicate()
print("output: " + out_ns)
print("error: " + err)
输出如下:
输出:
错误:
但在终端中,它会显示如下输出:
来自服务器的错误(已经存在):命名空间“namespace-tests”已经存在
如何将这个错误添加到我的err 变量中?
【问题讨论】:
-
在子进程中运行
grep无论如何都是愚蠢的。只需re.search(r'(?:^|\s){}(?:\s|$)'.format(NAMESPACE))上的stdout来自subprocess.run(['kubectl', 'get', 'ns'], text=True, capture_output=True) -
你能给我一个工作示例吗?我是 python 新手。
-
我几乎做到了。您在哪些部分遇到问题?另见stackoverflow.com/a/51950538/874188
-
...但是如果您要查找的是错误消息,则应该检查
stderr。 -
这里的
re是什么?
标签: python python-2.7 subprocess