我想在Python程序的运行之间保存一组键值对(字符串,整数),在后续运行时重新加载它们,并将更改写入下次运行时可用.
我不认为这些数据是配置文件,但它很适合ConfigParser功能.我只需要两个[部分].它只有几百对而且非常简单,所以我认为不需要做一个真正的数据库.
以这种方式使用ConfigParser是否合适?我也考虑过使用Perl和XML :: Simple.那个怎么样?有没有办法在没有Python或Perl的bash中执行此操作?
我有一个python类,它使用ConfigParser读取配置文件:
配置文件:
[geography]
Xmin=6.6
Xmax=18.6
Ymin=36.6
YMax=47.1
Run Code Online (Sandbox Code Playgroud)
Python代码:
class Slicer:
def __init__(self, config_file_name):
config = ConfigParser.ConfigParser()
config.read(config_file_name)
# Rad the lines from the file
self.x_min = config.getfloat('geography', 'xmin')
self.x_max = config.getfloat('geography', 'xmax')
self.y_min = config.getfloat('geography', 'ymin')
self.y_max = config.getfloat('geography', 'ymax')
Run Code Online (Sandbox Code Playgroud)
我觉得最后四行是重复的,并且应该以某种方式压缩到一个Pythonic线,这将self.item为该部分中的每个项创建一个变量.
有任何想法吗?
亚当
更新:
根据您的回答,我已将我的代码修改为:
for item in config.items('geography'):
setattr(self, '_'+item[0], float(item[1]))
Run Code Online (Sandbox Code Playgroud)
现在,
print self.__dict__
>>> {'_xmax': 18.600000000000001, '_ymax': 47.100000000000001,
'_ymin': 36.600000000000001, '_xmin': 6.5999999999999996}
Run Code Online (Sandbox Code Playgroud) 我正在为Web待办事项列表服务开发CLI。我已经完成了后端工作,并且刚刚开始编写CLI函数。在开始之前,我将介绍存储用户数据的最佳方法是什么。我正在使用ConfigParser来存储用户指定的偏好。这些存储在中~/.confrc。
用户数据采用Json的形式。我在我的项目中使用Python。我以以下形式获得这些:
{"user_id": 1, "name": "Project_name", "color": "#ff8581", "collapsed": 0, "item_order": 1, "cache_count": 13, "indent": 1, "id": 455831}
Run Code Online (Sandbox Code Playgroud)
我是否应该将此数据存储到配置文件中,该文件将通过ConfigParser处理?起初这可能是个好主意,但是一个项目可能具有另一个项目使用的名称。因此,我无法通过RawConfigParser.set()存储它们。我可以通过id存储它们,因为它们是唯一的,但是conf文件本身会很混乱。
存储简单的待办事项用户数据的最佳方法是什么?
我正在使用Python 3.2和configparser模块,并遇到一些问题.我需要阅读,然后写入配置文件.我尝试了以下方法:
import configparser
data = open('data.txt', 'r+')
a = configparser.ConfigParser()
a.read_file(data)
a['example']['test'] = 'red'
a.write(data)
问题是,当我用r +打开数据时,当我写入数据时,新信息会被追加; 它不会覆盖旧的.
import configparser
data = open('data.txt', 'r')
a = configparser.ConfigParser()
a.read_file(data)
a['example']['test'] = 'red'
data = open('data.txt', 'w')
a.write(data)
这样^似乎不安全,因为打开它会清空文件.如果程序在有时间写入之前崩溃怎么办?配置文件丢失.在用w打开之前,唯一的备份解决方案是什么?
编辑:
以下也是可能的,但是安全吗?
a.write(open('data.txt','w'))
Run Code Online (Sandbox Code Playgroud) 我最近编写了一个 Python 2.7 脚本(在 Eclipse 上使用 PyDev),它利用了内置的 ConfigParser 模块,并且该脚本运行良好。但是当我将它导出并发送给同事时,他无法让它工作。即使我们使用完全相同的设置,他也不断收到“未解析的导入:ConfigParser”错误。这不应该发生,因为 ConfigParser 是内置的。
我到处谷歌搜索,但似乎找不到任何可行的解决方案。任何帮助,将不胜感激。
我需要在Python中读取一个ini配置文件,以及来自development.ini相关部分的相关示例如下:
[app:main]
use = egg:ePRO
pyramid.reload_templates = true
pyramid.debug_authorization = false
pyramid.debug_notfound = true
pyramid.debug_routematch = true
pyramid.debug_templates = true
sqlalchemy.url = postgres://scott:tiger@localhost:5432/db
Run Code Online (Sandbox Code Playgroud)
我正在使用该ConfigParser模块读取文件,但无法sqlalchemy.url从INI文件中读取参数,
config = ConfigParser.ConfigParser()
config.read(config_uri)
Run Code Online (Sandbox Code Playgroud)
如何sqlalchemy.url从中读取参数[app:main]?
我已经使用“pip install configparser”安装了 configparser 来获取 configparser-3.5.0,并且在我的 PYTHONPATH 上。但是当我将它用作“import configparser”时,我看到一个错误“No module named backports.configparser”。conigparser.py 使用这个 'backports' 模块,我在 python 路径下看到了 'backports' 模块,但不知何故它无法识别该模块。有人可以告诉我如何解决这个问题吗?这在我看来肯定是 configparser 的一些版本问题,但到目前为止我没有找到任何答案。帮助将不胜感激,谢谢
我有一个使用python和Robotframework脚本混合实现的项目.我的项目Config.ini文件中存储了一堆配置项,如下所示:
[Environment]
Username: username@mail.com
Password: testpassword
[WebUI]
login_url: http://testsite.net/
Run Code Online (Sandbox Code Playgroud)
Python能够使用ConfigManager对象解释上述变量,如下所示:
class MyConfigManager(ConfigManager):
"""
Class to hold all config values in form of variables.
"""
def __init__(self):
super().__init__("dispatch/config.ini")
self._android = Android(self._config)
@property
def username(self):
return self._config.get(_env_section, "Username")
@property
def password(self):
return self._config.get(_env_section, "Password")
config = MyConfigManager()
Run Code Online (Sandbox Code Playgroud)
是否可以将Robotframework中的config.ini导入为变量文件并使用这些值?我正在尝试不为我的Robot脚本提供另一个变量文件.
编辑:
我试图用我的机器人文件做这样的事情:
*** Settings ***
Documentation WebUI Login Tests
Library SeleniumLibrary
Resource common_keywords.robot
Variables config.ini
# ^ will this work?
Default Tags Smoke
Suite Setup Set Selenium Timeout 15seconds
Suite Teardown Close Browser
*** …Run Code Online (Sandbox Code Playgroud) 我创建了一个类似.ini的文件,其中包含我稍后在程序中需要的所有值,如下所示:
[debugging]
checkForAbort = 10
...
[official]
checkForAbort = 30
...
Run Code Online (Sandbox Code Playgroud)
我想将所有这些项目读入一个类,并使其可以从我的python项目的其他部分访问.到目前为止,我的代码如下:
from ConfigParser import SafeConfigParser
import glob
class ConfigurationParameters
def __init__(self):
self.checkForAbortDuringIdleTime = None
parser = SafeConfigParser()
# making a list here in case we have multiple files in the future!
candidatesConfiguration = ['my.cfg']
foundCandidates = parser.read(candidatesConfiguration)
missingCandidates = set(candidatesConfiguration) - set(found)
if foundCandidates:
print 'Found config files:', sorted(found)
else
print 'Missing files :', sorted(missing)
print "aborting..."
# check for mandatory sections below
for candidateSections in ['official', 'debugging']:
if …Run Code Online (Sandbox Code Playgroud) 我有一个属性文件
Configuration.properties
path=/usr/bin
db=mysql
data_path=/temp
Run Code Online (Sandbox Code Playgroud)
我需要读取此文件并在后续脚本中使用路径,db和data_path等变量.我可以使用configParser或只是读取文件并获取值.提前致谢.
configparser ×10
python ×10
coding-style ×1
dry ×1
perl ×1
pydev ×1
pyramid ×1
python-2.7 ×1
read-write ×1
sqlalchemy ×1
xml ×1