我最近开始使用ConfigParser()为我的python脚本添加一些功能给它们配置文件.我知道如何使用它,但我有一个问题.我的脚本需要使用sudo作为root用户运行.配置文件在,~/.config/scriptconfig/但是当您以sudo身份运行脚本时,它会临时将用户更改为root,因此它找不到配置文件.我想要做的是获取有效用户的配置文件,以便抓取/home/myuser/.config/scriptconfig/config.cfg而/root/.config/scriptconfig/config.cfg不是存在.
我需要脚本能够在不同的机器上运行,而不仅仅是我的.所以我需要获得有效用户的主目录
这是我尝试使用的代码示例:
import os, ConfigParser
config = ConfigParser.RawConfigParser()
homepath = os.path.expanduser("~/")
configpath = homepath + ".config/scriptconfig/config.cfg"
config.read(configpath)
get = config.get('Config', 'Example')
print get
它应该打印example配置文件的值,但是当以sudo身份运行时,路径是/home/root这样,它找不到配置文件. 我正在研究一个简单的python脚本.它使用urllib从网页读取并将其转换为字典.Web服务器输出的方式是字典,因为它使用JSON.这是我有的:
import urllib2
d = 'http://www.somewebserver.com/tools/dictionary.php?string=hello'
r = urllib2.urlopen(d)
data = r.read()
r.close()
dictionary = dict(data)
print dictionary
唯一的问题是当我运行它时我得到这个错误:
Traceback (most recent call last):
File "get.py", line 6, in getstring()
dictionary = dict(data)
ValueError: dictionary update sequence element #0 has length 20; 2 is required
我如何成功地将其变成字典? 我正在尝试将拆分列表添加到另一个列表中.例如,我有这个列表:
['T', 'e', 's', 't', '\n', 'List', '\n']现在我想加入这些看起来像
['Test', 'List']我怎样才能做到这一点?