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

2024-04-23 19:43:28 发布

您现在位置: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)

Tags: 文件intxtcmd参数syslineproc
2条回答

比如:

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

otherIps包含list上的ip地址,然后需要检查theIp是否已经在otherIps上,如果已经存在,请退出脚本。你知道吗

如果文件不太大,可以执行以下操作:

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

现在,如果文件很大,并且希望避免可能的内存问题,可以使用^{},如下所示:

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。你知道吗

相关问题 更多 >