我正在运行一个脚本,它带有一个文本“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文件中特殊字符的文本。
看起来像%
字符是这里的问题。如果你使用ConfigParser
它有特殊意义。如果你没有使用插值,那么只使用RawConfigParser
,否则你必须通过加倍来逃避%
。
当我尝试使用ConfigParser
的示例文件时,它将会出现以下异常:
InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%19u^l\\&G"'
如果我用ConfigParser
替换RawConfigParser
一切都很好。
您发布的错误与此无关。我们甚至无法判断它是python异常还是shell错误消息。请使用完整的错误消息更新您的问题。你也可以want to check the sh
module,subprocess
周围的更高层包装。
加上Paulo Scardine的评论。
如果你有需要处理的特殊字符,你可以将ConfigParser
的interpolation
参数设置为None
,你将不再有错误。 ConfigParser
默认将interpolation
设置为BasicInterpolation()
。
你可以在这里阅读更多相关信息:https://docs.python.org/3.6/library/configparser.html#interpolation-of-values
此外,根据文件RawConfigParser
是Legacy 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
的值。