Python:ConfigParser.NoSectionError:没有部分:'电子邮件'

时间:2016-01-06 18:57:54

标签: python configparser

我得到了KeyError: 'E-mail'。但找不到问题。我尝试了readfp()以及使用文件的完整路径。 my_file = (os.path.join(os.getcwd(),'config.ini'))。但似乎没有任何效果。

这是代码。

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
from=random@gmail.com
password=******

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

1 个答案:

答案 0 :(得分: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

一切都很好。

相关问题