python从输出中提取几行

python从输出中提取几行,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,我创建了一个python类来执行curl命令,该命令反过来生成一个令牌。代码按预期工作。脚本生成预期的输出。现在,需要以下提到的输出中的几行,而不是整个输出 如何从输出中提取以下行 lines starting after Set-Cookie: SESSION= till =; 。如何提取这些行 import requests import json from akamai.edgegrid import EdgeGridAuth, EdgeRc

我创建了一个python类来执行curl命令,该命令反过来生成一个令牌。代码按预期工作。脚本生成预期的输出。现在,需要以下提到的输出中的几行,而不是整个输出

如何从输出中提取以下行

lines starting after 
Set-Cookie: SESSION=   till  =;  
。如何提取这些行

    import requests
    import json
    from akamai.edgegrid import EdgeGridAuth, EdgeRc
    from tabulate import tabulate
    import os
    import re
    import base64

    class generate_token(object):

        """
          This library is to generate token for the test application

        """

        def __init__(self,kwargs):

            self.username     = 'user'
            self.password     = 'abcdef'
            self.contractName = kwargs.get("Names")
            self.contractType = kwargs.get("Type")
            self.accountId    = kwargs.get("Id")
            self.env          = kwargs.get("env")

        def requestSession(self):

             if self.env == "test":
               ping = os.popen('ping -c 1  hostname.com').read()
               ip_addr  = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b",ping)[0]

             else:
                ping = os.popen('ping -c 1  different_hostname.com').read()
                ip_addr = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b",ping)[0]

             url = "https://%s/EdgeAuth/asyncUserLogin" %(ip_addr)
             command = "curl -is -v  -k  -d username=%s -d password=%s --request POST '%s' " %(self.username,self.password,url)
             self.session = os.popen(command).read()


if __name__ == "__main__":
    initData = {
                'Names': 'names',
                'Type': 'type',
                'Id': 'ID',
                'env' : 'test'
                }

    c = generate_token(kwargs=initData)
    result = c.requestSession()
全部输出:

* TCP_NODELAY set
* WARNING: disabling hostname validation also disables SNI.
> POST /EdgeAuth/asyncUserLogin HTTP/1.1
> Host: 143.111.112.202
> User-Agent: curl/7.54.0
> Accept: */*
> Content-Length: 33
> Content-Type: application/x-www-form-urlencoded
>
} [33 bytes data]
* upload completely sent off: 33 out of 33 bytes
< HTTP/1.1 302 Moved Temporarily
< Date: Thu, 26 Jul 2018 15:54:07 GMT
< Server: Apache-Coyote/1.1
< Location: https://192.168.93.201/homeng/view/main
< Content-Length: 0
< Set-Cookie: SESSION=1-7FOmRFhEcci+8fAfh+DvLg==-1bk61eksykUHbWc9kx3LzL0KdkaxyDodxsEsu6siMR/1cpR7yLaD7HtTjXEr+XDowzpYcug4bfKIMjk2/T0aqJiHg5BrbRbnBeZnTcAUIpdyKGvtnmEQkSADoaxvgfYGrxqQctrVPdqJtPziqvIbjO1X8xh0Xtj/ZNvJXaSFs//w9ISNZ5hvIDBygUo+0EuYT8PSTYVPrcBCLaJUkC8ACg==-jdN937gosTsMx8fdaJqP5sA7wKPRgqv1RxRkX65SWeE=; 
Path=/; Secure
< Via: 1.1 %{HTTP_HOST}
< X-Content-Type-Options: nosniff
< Content-Type: text/plain

不要使用
os.popen
和friends来执行外部程序-使用
子流程
模块来执行:

ping = subprocess.check_output(['ping', '-c', '1', 'hostname.com'])
同样,不要仅仅为了从url获取cookie而执行子流程-您已经在代码中导入了优秀的
请求
库,为什么不使用它呢

r = requests.post(url, data={'username': self.username, 'password': self.password})
print (r.cookies['SESSION'])

r.cookies在哪里?在输出中,我看到设置Cookie,但没有设置Cookie。如何使用regex执行此操作?@AHB
r.cookies
是来自
请求
库的响应对象的一个属性-库将收集所有Cookie并放入一个类似dict的对象中,以便您轻松访问!请参阅此处的文档regex用于按照非嵌套模式提取文本片段-它根本不足以解决此问题@AHB-相反,您应该使用解析器-一个
请求
库中已经包含的解析器。我得到了关键错误。Cookie无法找到会话。文件“/usr/local/lib/python2.7/site packages/requests/cookies.py”,第400行,在“查找不到重复项”中,引发KeyError('name=%r,domain=%r,path=%r%%(name,domain,path))KeyError:“name='SESSION',domain=None,path=None”
r = requests.post(url, data={'username': self.username, 'password': self.password})
print (r.cookies['SESSION'])