繁体   English   中英

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

[英]Python: ConfigParser.NoSectionError: No section:'E-mail'

我收到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中尝试了很多相同的问题。 但是没有运气。

我无法重现您的错误。 我要说的是,您的配置文件解析代码没有错。

可能您的配置文件中有错字。 您确定已阅读您认为已阅读的文件吗?

我已经设置了以下配置文件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

一切顺利。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM