检查命令行参数是否已被使用

时间:2016-12-18 14:04:10

标签: python

我试图检查IP地址(参数)的反向查找。然后将结果写入txt文件。  我如何检查IP地址(参数)是否已在文件中注册?如果是这样,我需要退出剧本。

我的剧本:

import sys, os, re, shlex, urllib, subprocess 

cmd = 'dig -x %s @192.1.1.1' % sys.argv[1]

proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)
out, err = proc.communicate()

# Convert to list of str lines
out = out.decode().split('\n')

# Only write the line containing "PTR"
with open("/tmp/test.txt", "w") as f:
 for line in out:
    if "PTR" in line:
        f.write(line)

2 个答案:

答案 0 :(得分:1)

如果文件不是太大,你可以这样做:

with open('file.txt','r') as f:
    content = f.read()
if ip in content:
    sys.exit(0)

现在,如果文件很大并且您想避免可能的内存问题,可以使用mmap,如下所示:

import mmap
with open("file.txt", "r+b") as f:
    # memory-map the file, size 0 means whole file
    mm = mmap.mmap(f.fileno(), 0)
    if mm.find(ip) != -1: 
        sys.exit(0)

mmap.find(string[, start[, end]])已有详细记录here

答案 1 :(得分:0)

类似的东西:

otherIps = [line.strip() for line in open("<path to ipFile>", 'r')]
theIp = "192.168.1.1"
if theIp in otherIps:
    sys.exit(0)

otherIps在[{1}}上包含list个IP地址,然后您需要检查ipFile上是否已theIp,如果是,请退出脚本。