Python 2.7名称错误:未定义名称“servervpn”

2024-05-23 14:03:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将文件中的一行文本存储到变量中:

#!/usr/bin/python

fo=open("/home/asb/crt/id2tcpvpncom443.ovpn")
for line in fo:
  if line.find('remote')==0:
    vpn=line.split(" ")
    if len(vpn) > 1:
      servervpn=vpn[1] + ":" + vpn[2]
      hostvpn=vpn[1]
      portvpn=vpn[2]
print 'server: '+servervpn

/home/asb/crt/id2tcpvpncom443.ovpn如下所示:

^{pr2}$

我希望结果是:

server: 188.166.179.165:443

我该怎么做?在

编辑:

实际上id2tcpvpncom443.ovpn比这个长得多,下面是我要读的完整文件:http://pastebin.com/PNphqXtt


Tags: 文件文本homeifbinserverusrline
3条回答

我更像Python:

with open('your_file', 'r') as fp:
    # this is the right way to open a file
    for line in fp:
        if line.startswith('remote ') and line.count(' ') >= 3:
            _, ip, port = line.split() # split to every word seperator
            print ip, port

这里是您的代码稍微修改一下,使其工作

#!/usr/bin/python

fo=open("/home/asb/crt/id2tcpvpncom443.ovpn")
for line in fo:
    if line.strip().startswith('remote'): # startswith is a bit more direct here
        vpn=line.split() # split without argument splits at any whitespace
        if len(vpn) > 2: # not necessary but defensive -> good
            servervpn=vpn[1]
            hostvpn=vpn[1]
            portvpn=vpn[2]
            # if you like you can short-circuit here:
            break

print 'server: ' + ':'.join([servervpn, portvpn])

你在一个空格字符上拆分;如果你的分隔是两个空格或一个制表符,事情就不会如预期的那样工作。相反,在(通用)空白处拆分:

vpn=line.split()

相关问题 更多 >