从python中的.ini文件中读取特殊字符文本

问题描述 投票:4回答:2

我正在运行一个脚本,它带有一个文本“rAh%19u ^ l \&G”,其中包含所见的特殊字符。

当我在我的脚本中将此文本作为参数传递时,它运行正常,没有任何错误。

示例 - :./abc.py <username><pwd>

以上文字基本上是一个密码。

现在,当我将我的值放在配置文件中并阅读上面的文本时,脚本失败了。

******* abc.ini *******

[DEFAULT]
username = rahul
pwd =  rAh%19u^l\&G

它说

/bin/sh:M command not found.

在配置解析器的帮助下阅读上述值

******以下是程序abc.py ******

#! /usr/bin/python

parser = configparser.ConfigParser()
parser.read('abc.ini')
username = parser.get('DEFAULT','username')
pwd = parser.get('DEFAULT','pwd')


p = subprocess.Popen(
    "abc.py {0} {1}" .format(username, pwd), 
    shell=True, 
    stdout=subprocess.PIPE
)

out, err = p.communicate()

print(out)

我试了很多,但没有找到具体的东西。

所以问题是如何读取包含.ini文件中特殊字符的文本。

python configparser
2个回答
9
投票

看起来像%字符是这里的问题。如果你使用ConfigParser它有特殊意义。如果你没有使用插值,那么只使用RawConfigParser,否则你必须通过加倍来逃避%

当我尝试使用ConfigParser的示例文件时,它将会出现以下异常:

InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%19u^l\\&G"'

如果我用ConfigParser替换RawConfigParser一切都很好。

您发布的错误与此无关。我们甚至无法判断它是python异常还是shell错误消息。请使用完整的错误消息更新您的问题。你也可以want to check the sh modulesubprocess周围的更高层包装。


1
投票

加上Paulo Scardine的评论。

如果你有需要处理的特殊字符,你可以将ConfigParserinterpolation参数设置为None,你将不再有错误。 ConfigParser默认将interpolation设置为BasicInterpolation()

你可以在这里阅读更多相关信息:https://docs.python.org/3.6/library/configparser.html#interpolation-of-values

此外,根据文件RawConfigParserLegacy variant of the ConfigParser with interpolation disabled by default and unsafe add_section and set methods.

这是一个片段:

例:

[Paths]
home_dir: /Users
my_dir: %(home_dir)s/lumberjack
my_pictures: %(my_dir)s/Pictures

在上面的示例中,插值设置为BasicInterpolation()的ConfigParser会将%(home_dir)s解析为home_dir(在本例中为/ Users)的值。 %(my_dir)s实际上将解决/Users/lumberjack。 [....]

在插值设置为None时,解析器将简单地返回%(my_dir)s/Pictures作为my_pictures%(home_dir)s/lumberjack的值作为my_dir的值。

© www.soinside.com 2019 - 2024. All rights reserved.