【问题标题】:How to stop Python 2.7 RawConfigParser throwing ParsingError on tabs?如何阻止 Python 2.7 RawConfigParser 在选项卡上抛出 ParsingError?
【发布时间】:2017-07-31 12:14:03
【问题描述】:

我正在编写一个与Python 2.7.13Python 3.3 兼容的包,并使用以下内容:

try:
    import configparser
except:
    from six.moves import configparser

但是当我在Python 2.7 上加载我的.gitmodules 文件时:

    configParser   = configparser.RawConfigParser( allow_no_value=True )
    configFilePath = os.path.join( current_directory, '.gitmodules' )

    configParser.read( configFilePath )

它抛出错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "update.py", line 122, in run
    self.create_backstroke_pulls()
  File "update.py", line 132, in create_backstroke_pulls
    configParser.read( configFilePath )
  File "/usr/lib/python2.7/ConfigParser.py", line 305, in read
    self._read(fp, filename)
  File "/usr/lib/python2.7/ConfigParser.py", line 546, in _read
    raise e
ParsingError: File contains parsing errors: /cygdrive/d/.gitmodules
        [line  2]: '\tpath = .versioning\n'
        [line  3]: '\turl = https://github.com/user/repo\n'

但如果我从.gitmodules 文件中删除选项卡,它就可以正常工作。在Python 3.3 上,它可以与选项卡一起使用,仅在Python 2.7.13 上,它不能与选项卡一起使用。如何在不删除标签的情况下使其工作?

当我添加新的子模块时,这些标签是由git 本地放置的,所以我绝对不会从原始文件中删除它们。我一直在想我可以复制文件,同时删除标签。但是与Python兼容的操作成本更低吗?


相关问题:

  1. How can I remove the white characters from configuration file?

【问题讨论】:

    标签: python git python-2.7 tabs python-3.3


    【解决方案1】:

    一种解决方法是使用带有修改内容的io.StringIO 传递给readfp(它接受文件句柄而不是文件名)。

    以下代码试图同时符合 Python 2 和 Python 3(即使在 Python 3 中,readfp 已被弃用,现在它是 read_file。无论如何它仍然有效)。请注意,我不需要 six 包,configparser 原生存在于 2 和 3 个 python 版本中。

    try:
        import ConfigParser as configparser
    except ImportError:
        import configparser
    
    import io
    try:
        unicode
    except NameError:
        unicode = str  # python 3: no more unicode
    
    r = configparser.RawConfigParser()
    
    with open(configFilePath) as f:
        fakefile = io.StringIO(unicode(f.read().replace("\t","")))
    
    r.readfp(fakefile,filename=configFilePath)
    

    所以解析器通过读取文件内容减去标签的虚假文件而被“愚弄”。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多