gpt4 book ai didi

python - 如何查看某些内容(变量)是否已设置?

转载 作者:太空宇宙 更新时间:2023-11-03 17:54:14 25 4
gpt4 key购买 nike

这是我的代码:

for msg in mbox:
try:
pprint.pprint(msg._headers, stream = f)
tempdate = parser.parse(msg['Date'])
newdate = str(tempdate)[:19]
ip = msg['x-originating-ip']
iplookup = (ip.strip("[]"))
url = 'http://freegeoip.net/json/{}'.format(iplookup)
response = urllib.request.urlopen(url).read()
result = json.loads(response.decode('utf8'))
f.write ('Country = ' + (result['country_name']) + '\n')
f.write ('Region = ' + (result['region_name']) + '\n')
f.write ('City = ' + (result['city']) + '\n')

但是,并非所有电子邮件都有原始 IP。我如何检查 x 组织 IP 是否已设置?类似 IF 语句的东西

       ip = msg['x-originating-ip']

if (isset(ip):
iplookup = (ip.strip("[]"))
url = 'http://freegeoip.net/json/{}'.format(iplookup)
response = urllib.request.urlopen(url).read()
result = json.loads(response.decode('utf8'))
f.write ('Country = ' + (result['country_name']) + '\n')
f.write ('Region = ' + (result['region_name']) + '\n')
f.write ('City = ' + (result['city']) + '\n')
else:
continue

这是我想到的一个例子,但是isset函数来自php,而不是python?有什么想法吗?

最佳答案

尝试

if 'x-originating-ip' in msg:
...

它使用in operator 。它只检查键是否已设置,而不检查值是什么 - 因此它仍然可以是 NoneFalse 或空字符串或列表或其他内容。您还可以使用 'foo' not in x 代替 not 'foo' in x

如果您想同时检查它是否不是None,例如,使用 get()相反:

if msg.get('x-originating-ip') is not None:
...

关于python - 如何查看某些内容(变量)是否已设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28721866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com