如何仅打印python cu的输出

2024-10-01 15:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python执行此bash命令并获取输出:

这是我正在使用的命令:

cmd_ = "curl -k -X GET https://consul.cicdtest.us-east-1.dev:8543/v1/kv/" +constants.NAMESPACE+"/"+constants.CONSUL_KEY+"?token="+decode_token

我执行上面的cmd_如下:

process = Popen(cmd_, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
output = process.stdout.read()    
print(output)

我得到如下输出(工作正常):

% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   144  100   144    0     0   5142      0 --:--:-- --:--:-- --:--:--  5142

[{"LockIndex":0,"Key":"bitesize-troubleshooter-2/CONSUL_TEST-2","Flags":0,"Value":"dGVzdF9kYXRhLTI=","CreateIndex":338871,"ModifyIndex":341651}]

我需要的唯一输出是:

[{"LockIndex":0,"Key":"bitesize-troubleshooter-2/CONSUL_TEST-2","Flags":0,"Value":"dGVzdF9kYXRhLTI=","CreateIndex":338871,"ModifyIndex":341651}]

但不知怎的,我得到了这样的标题:

% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   144  100   144    0     0   5142      0 --:--:-- --:--:-- --:--:--  5142

如何删除这个类似头的东西并只访问下面输出中的Value?你知道吗

[{"LockIndex":0,"Key":"bitesize-troubleshooter-2/CONSUL_TEST-2","Flags":0,"Value":"dGVzdF9kYXRhLTI=","CreateIndex":338871,"ModifyIndex":341651}]

我真正想从上面的输出中得到的是Value


Tags: keytestcmdtimevaluetotalflagsspeed
2条回答

curl -s使Curl保持沉默。你知道吗

-s, silent Silent or quiet mode.
Don't show progress meter or error messages. Makes Curl mute. It will still output the data you ask for, potentially even to the terminal/stdout unless you redirect it.

然而,这里的实际问题是您正在设置stderr=STDOUT,因此通常打印到标准错误流的进度表被重定向到您正在捕获的标准输出流。你知道吗

你也会想摆脱它。你知道吗

因为已经有了python脚本,所以可以使用python进行curl调用。这样你就可以得到你想要的响应的内容,而且比从stdout中过滤出来更好。下面是python3语法

import requests

response = requests.get(f"https://consul.cicdtest.us-east-1.dev:8543/v1/kv/{constants.NAMESPACE}/{constants.CONSUL_KEY}?token={decode_token}")
print(response.content)

下面是python2.7语法

import requests
url =  "https://consul.cicdtest.us-east-1.dev:8543/v1/kv/" +constants.NAMESPACE+"/"+constants.CONSUL_KEY+"?token="+decode_token
response = requests.get(url)
print response.content

相关问题 更多 >

    热门问题