Python 2.6 - 传递| char进入os.system in for循环

D3l*_*ato 0 python for-loop os.system

我有一个IP列表,我想运行一个whois(使用linux工具whois),只看到Country选项.

这是我的脚本:

import os
import time

iplist = open('ips.txt').readlines()

for i in iplist:
        time.sleep(2)
        print "Country: IP {0}".format(i)
        print os.system("whois -h whois.arin.net + {0} | grep Country ".format(i))
Run Code Online (Sandbox Code Playgroud)

所以我想显示正在运行的IP,然后我只想使用grep查看Country信息.我运行它并且没有运行grep时看到这个错误:

sh: -c: line 1: syntax error near unexpected token `|'
sh: -c: line 1: ` | grep Country '
Run Code Online (Sandbox Code Playgroud)

下面这段代码是有效的,所以它必须是我的for循环的一个问题:

 print os.system("whois -h whois.arin.net + {0} | grep Country ".format('8.8.8.8'))
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?谢谢!!!!

use*_*342 6

您没有从您从文件中读取的行中删除尾随换行符.结果,你传递给os.system像一个字符串"whois -h whois.arin.net + a.b.c.d\n | grep Country".shell将字符串解析为两个命令并抱怨"意外令牌" 在第二个开头.这解释了为什么使用手工制作的字符串时没有错误"8.8.8.8".

i = i.strip()睡眠后添加,问题就会消失.