2016-01-06 129 views
0

我得到KeyError: 'E-mail'。但找不到问题。我试过readfp()以及使用文件的完整路径。 my_file = (os.path.join(os.getcwd(),'config.ini'))。但似乎没有任何工作。Python:ConfigParser.NoSectionError:没有部分:'电子邮件'

这是代码。

import configparser 
import sys 
import xml.etree.ElementTree as ET 
import time 
import smtplib 
import os 

def usage(code): 
    sys.stderr.write("usage:\n") 
    sys.stderr.write(" " + sys.argv[0] + " <xml file with addresses> <subject> <file with message body>\n") 
    sys.exit(code) 


cfg = configparser.ConfigParser() 
cfg.read('config.ini') 

server = cfg.get('E-mail', 'server') 
login = cfg.get('E-mail', 'login') 
from_addr = cfg.get('E-mail', 'from') 
password = cfg.get('E-mail', 'password') 

if len(sys.argv) < 4: 
    usage(1) 

src_xml = sys.argv[1] 
subject = sys.argv[2] 
msg_file = sys.argv[3] 

server = smtplib.SMTP(server) 
server.ehlo() 
server.starttls() 
server.login(login, password) 

with open(msg_file) as f: 
    msg_text = f.read() 

tree = ET.parse(src_xml) 
root = tree.getroot() 

for p in root: 
    if 'email' in p.attrib: 
    to_addr = p.attrib['email'] 
    msg = "\r\n".join([ 
     "From: " + from_addr, 
     "To: " + to_addr, 
     "Subject: " + subject, 
     "", 
     msg_text 
    ]) 
    server.sendmail(from_addr, to_addr, msg) 

server.quit() 

这里是我得到的错误。

Traceback (most recent call last): 
    File "C:\Users\Isuru\AppData\Local\Programs\Python\Python35-32\lib\configparser.py", line 1135, in _unify_values 
    sectiondict = self._sections[section] 
KeyError: 'E-mail' 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "C:\Users\Isuru\Desktop\script\MailSender.py", line 17, in <module> 
    server = cfg.get('E-mail', 'server') 
    File "C:\Users\Isuru\AppData\Local\Programs\Python\Python35-32\lib\configparser.py", line 778, in get 
    d = self._unify_values(section, vars) 
    File "C:\Users\Isuru\AppData\Local\Programs\Python\Python35-32\lib\configparser.py", line 1138, in _unify_values 
    raise NoSectionError(section) 
configparser.NoSectionError: No section: 'E-mail' 

这是config.ini文件。

[E-mail] 
server=********:465 
login=***********.com 
[email protected] 
password=****** 

我在StackOverflow中尝试了很多相同的问题。但没有运气。

+1

请删除脚本中的所有其他代码,只保留最少的解析部分,然后查看错误是否消失。那么请仅在这里发布这个部分。 – moooeeeep

+0

嗯,我试过了。问题在于解析部分。 – Isuru

+0

尝试没有破折号。 – PsyKzz

回答

1

我无法重现您的错误。我甚至可以说你的配置文件解析代码没有问题。

也许你的配置文件中有一个错字。你确定你读过你认为你读过的文件吗?

我已经设置了以下配置文件conf.ini

[E-mail] 
foo=hello 
bar=world 

而下面的Python 3脚本test.py

from configparser import ConfigParser 
parser = ConfigParser() 
parser.read("conf.ini") 
print(parser.get("E-mail", "foo")) 
print(parser.get("E-mail", "bar")) 

当我运行该脚本,我得到以下的输出:

$ python3 test.py 
hello 
world 

一切都很好。