[英]Get only stdout in a variable in python using subprocess
我在cli中使用以下命令,如下所示:
[mbelagali@mbelagali-vm naggappan]$ aws ec2 create-vpc --cidr-block 172.35.0.0/24 --no-verify-ssl --endpoint-url https://10.34.172.145:8787
/usr/local/aws/lib/python2.6/site-packages/botocore/vendored/requests/packages/urllib3/connectionpool.py:769:
InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
"Vpc": {
"InstanceTenancy": "default",
"State": "pending",
"VpcId": "vpc-ebb1608e",
"CidrBlock": "172.35.0.0/24",
"DhcpOptionsId": "dopt-a24e51c0"
}
現在,我使用“ 2> / dev / null”重定向警告,以便僅獲得json響應。
現在,我需要使用python子進程來實現此功能,因此嘗試了以下選項,
cmd = "aws ec2 create-vpc --cidr-block " + cidr_block + " --no-verify-ssl --endpoint-url " + endpoint_url
cmd_arg = shlex.split(cmd.encode('utf-8'))
p1 = subprocess.Popen(
cmd_arg,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
output, error = p1.communicate()
現在在輸出變量中,我得到的是包含警告消息的完整輸出,如何像在shell腳本中那樣忽略警告消息
如果您不想要stderr消息,則不應具有標志stderr=subprocess.STDOUT
,該標志等效於2>&1
。 如果您只是刪除,我懷疑您會得到想要的。 如果要將stderr重定向到/ dev / null,可以遵循以下答案: 如何在Python 2.7中隱藏子進程的輸出
要分離stderr和stdout,只需創建兩個獨立的管道即可。
p1 = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
要完全忽略stderr,只需打開devnull並在那里重定向stderr。
with open(os.devnull) as devnull:
p1 = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=devnull)
os.devnull空設備的文件路徑。 例如:POSIX為'/ dev / null',Windows為'nul'。 也可以通過os.path獲得。
要獲取子進程打印到其stdout的json數據,而忽略其stderr上的警告:
from subprocess import check_output
json_data = check_output(cmd, stderr=DEVNULL)
此處定義DEVNULL
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.