Python Popen WHOIS 操作系统命令失败测试
开头先说一句“我只是个初学者”。当你通过Popen命令得到whois命令的结果时,怎么判断这个结果是否有效呢?
通常在Python中,当返回一个列表时,我可以测试一下这个列表的长度,这样通常就够用了,但这次情况有点复杂。
比如,我在测试一个域名的来源国家,但有时候通过gethostbyaddr得到的域名在WHOIS服务器上并不被识别。所以,我想试试发送一个IP地址来应对这种情况,但最后得到的测试代码不太好看,字符数还不到70。我只是想知道,大家有没有什么“标准”的方法来处理这个问题。
w = Popen(['whois', domain], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
whois_result = w.communicate()[0]
print len(whois_result)
if len(whois_result) <= 70:
w = Popen(['whois', p_ip], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
whois_result = w.communicate()[0]
print len(whois_result)
if len(whois_result) <= 70:
print "complete and utter whois failure, its you isnt it, not me."
test = re.search("country.+([A-Z].)",whois_result)
countryid = test.group(1)
1 个回答
1
直接回答你的问题,可以在 whois
命令的输出中查找这个字符串,看看是否有问题...
没有找到 "insert_domain_here"
关于你任务中的其他重要问题... 你的 Popen
命令做得有点复杂... 其实你不需要为 stdin
使用 PIPE
,而且可以直接在 Popen
上调用 .communicate()
,这样会更高效一些... 我根据我认为你想要的方式进行了重写...
from subprocess import Popen, PIPE, STDOUT
import re
## Text result of the whois is stored in whois_result...
whois_result = Popen(['whois', domain], stdout=PIPE,
stderr=STDOUT).communicate()[0]
if 'No match for' in whois_result:
print "Processing whois failure on '%s'" % domain
whois_result = Popen(['whois', p_ip], stdout=PIPE,
stderr=STDOUT).communicate()[0]
if 'No match for' in whois_result:
print "complete and utter whois failure, its you isnt it, not me."
test = re.search("country.+([A-Z].)",whois_result)
countryid = test.group(1)