Вопрос

Hello I was working on a new python script today and I ran into this error. Im a little confused about it, plus being new to scripting I dont know how to define this code. Any help would be wonderful. Thank you

Error

 File "newipemail.py", line 25, in <module>

    text = 'The IP address is: %s' % inet_string

NameError: name 'inet_string' is not defined

Script

#!/usr/bin/python

import subprocess
import smtplib
import string
import time

FIXED_IP = '10.10.2.10'

ipaddr_string = 'ip -4 addr > ~/current_ip.txt'
subprocess.call(ipaddr_string, shell=True)

ip_file = file('current_ip.txt', 'r')
for line in ip_file:
        if 'eth0:' in line:
            inet_line = ip_file.next()
            _time = time.asctime()
            inet_string = inet_line[9:(inet_line.index('/'))]
            if inet_string != FIXED_IP:
                print 'Found eth0: %s' % inet_string

SUBJECT = 'IP Address from Raspberry Pi at: %s' % time.asctime()
TO = 'user@emial.com'
FROM = 'pi@email.com'
text = 'The IP address is: %s' % inet_string
BODY = string.join((
    'From: %s' % FROM,
   'To: %s' % TO,
    'Subject: %s' % SUBJECT,'',text), '\r\n')

server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login('email.server.com', 'password')
server.sendmail(FROM, [TO], BODY)
server.quit()

ip_file.close()
Это было полезно?

Решение

The problem is that for the current line in current_ip.txt, the string eth0: is not found. Because of this, your if-statement returns False.

if 'eth0:' in line:
    inet_line = ip_file.next()
    _time = time.asctime()
    inet_string = inet_line[9:(inet_line.index('/'))]

If eth0: is found in line, inet_line is defined, otherwise it will not be defined and Python jumps to the next code block which is where the exception is raised.

text = 'The IP address is: %s' % inet_string

Другие советы

When I went into the file i had accidentally placed eth0 as eth1 I changed it back to eth0 and it worked great.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top