本文整理汇总了Python中settings.Settings.read方法的典型用法代码示例。如果您正苦于以下问题:Python Settings.read方法的具体用法?Python Settings.read怎么用?Python Settings.read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类settings.Settings
的用法示例。
在下文中一共展示了Settings.read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
def main(argv = None):
""" Guido van Rossum's pattern for a Python main function """
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "hl:o:",
["help", "limit=", "output="])
except getopt.error as msg:
raise Usage(msg)
limit = 10 # !!! DEBUG default limit on number of articles to parse, unless otherwise specified
# Process options
for o, a in opts:
if o in ("-h", "--help"):
print(__doc__)
return 0
elif o in ("-l", "--limit"):
# Maximum number of articles to parse
try:
limit = int(a)
except ValueError as e:
pass
elif o in ("-o", "--output"):
if a:
global OUTPUT_FILE
OUTPUT_FILE = a
else:
raise Usage("Output file name must be nonempty")
# Process arguments
for arg in args:
pass
# Read the configuration settings file
try:
Settings.read("config/ReynirSimple.conf")
# Don't run the processor in debug mode
Settings.DEBUG = False
except ConfigError as e:
print("Configuration error: {0}".format(e), file = sys.stderr)
return 2
process_articles(limit = limit)
except Usage as err:
print(err.msg, file = sys.stderr)
print("For help use --help", file = sys.stderr)
return 2
# Completed with no error
return 0
示例2: __init__
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
def __init__(self):
super(QtGui.QWidget, self).__init__()
self.setWindowTitle("SimpleShortcuts")
main_layout = QtGui.QVBoxLayout()
main_layout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.shortcut_layout = QtGui.QGridLayout()
bottom_layout = QtGui.QHBoxLayout()
settings_button = QtGui.QPushButton("Settings")
settings_button.clicked.connect(self.settings_button_clicked)
kill_button = QtGui.QPushButton("Kill Application")
kill_button.clicked.connect(partial(self.run, "xkill"))
bottom_layout.addWidget(kill_button)
bottom_layout.addStretch()
bottom_layout.addWidget(settings_button)
main_layout.addLayout(self.shortcut_layout)
main_layout.addLayout(bottom_layout)
self.setLayout(main_layout)
self.settings = Settings.read()
self.refresh_shortcuts()
示例3: settings_button_clicked
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
def settings_button_clicked(self):
s = SettingsDialog(self)
ret = s.exec_()
if ret == 1:
Settings.save(s.settings)
self.settings = Settings.read()
self.refresh_shortcuts()
示例4: main
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
def main():
""" Main program """
try:
Settings.read("config/Reynir.conf")
except ConfigError as e:
print("Configuration error: {0}".format(e), file = sys.stderr)
return 2
verbs = read_verbs("resources/sagnir.txt")
with changedlocale() as strxfrm:
verbs_sorted = sorted(verbs.values(), key = lambda x: strxfrm(x.nom))
print("#\n# Verb list generated by verbs.py from resources/sagnir.txt")
print("#", str(datetime.utcnow())[0:19], "\n#\n")
display(verbs_sorted)
print("\n# Total: {0} distinct verbs\n".format(len(verbs)))
# Check which verbs are missing or different in Verbs.conf
#count = check_missing(verbs_sorted)
#print("\n# Total: {0} missing verb forms\n".format(count))
return 0
示例5: main
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
def main(dev_size, train_size, shuffle, scores):
print("Welcome to the Reynir text and parse tree pair generator")
try:
# Read configuration file
Settings.read(os.path.join(basepath, "config/ReynirSimple.conf"))
except ConfigError as e:
print("Configuration error: {0}".format(e))
quit()
# Generate the parse trees from visible roots only,
# in descending order by time of parse
stats = { "parsed" : datetime.utcnow() }
gen = gen_simple_trees({ "order_by_parse" : True, "visible" : True }, stats)
if shuffle:
# Write both sets
written = write_shuffled_files(OUTFILE_DEV, OUTFILE_TRAIN, gen, dev_size, train_size, scores)
else:
# Development set
if dev_size:
print(f"\nWriting {dev_size} {'shuffled ' if shuffle else ''}sentences to {OUTFILE_DEV}")
written = write_file(OUTFILE_DEV, gen, dev_size, scores)
print(f"{written} sentences written")
# Training set
if train_size:
print(f"\nWriting {train_size} {'shuffled ' if shuffle else ''}sentences to {OUTFILE_TRAIN}")
written = write_file(OUTFILE_TRAIN, gen, train_size, scores)
print(f"{written} sentences written")
last_parsed = stats["parsed"]
print(f"\nThe last article processed was parsed at {last_parsed}")
print("\nPair generation completed")
示例6: simple_parse
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
def simple_parse(text):
""" No-frills parse of text, returning a SimpleTree object """
if not Settings.loaded:
Settings.read("config/Reynir.conf")
with SessionContext(read_only=True) as session:
return SimpleTree(*TreeUtility.parse_text(session, text))
示例7: _main
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
def _main(argv = None):
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "hl:van",
["help", "limit=", "verbose", "all", "notify"])
except getopt.error as msg:
raise Usage(msg)
limit_specified = False
limit = 10
verbose = False
process_all = False
notify = False
# Process options
for o, a in opts:
if o in ("-h", "--help"):
print(__doc__)
return 0
elif o in ("-l", "--limit"):
# Maximum number of articles to parse
try:
limit = int(a)
limit_specified = True
except ValueError as e:
pass
elif o in ("-v", "--verbose"):
verbose = True
elif o in ("-a", "--all"):
process_all = True
elif o in ("-n", "--notify"):
notify = True
#if process_all and limit_specified:
# raise Usage("--all and --limit cannot be used together")
Settings.read("Vectors.conf")
# Process arguments
if not args:
raise Usage("No command specified")
la = len(args)
arg = args[0]
if arg == "tag":
# Tag articles
uuid = args[1] if la > 1 else None
if la > (1 if uuid is None else 2):
raise Usage("Too many arguments")
if uuid:
if process_all:
raise Usage("Conflict between uuid argument and --all option")
if limit_specified:
raise Usage("Conflict between uuid argument and --limit option")
if process_all and not limit_specified:
limit = None
tag_articles(limit = limit, verbose = verbose, process_all = process_all, uuid = uuid)
if notify:
# Inform the similarity server that we have new article tags
notify_similarity_server()
elif arg == "topics":
# Calculate topics
if la > 1:
raise Usage("Too many arguments")
calculate_topics(verbose = verbose)
elif arg == "model":
# Rebuild model
if la > 1:
raise Usage("Too many arguments")
build_model(verbose = verbose)
else:
raise Usage("Unknown command: '{0}'".format(arg))
except Usage as err:
print(err.msg, file = sys.stderr)
print("For help use --help", file = sys.stderr)
return 2
# Completed with no error
return 0
示例8: timeit
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
sentence_stream = Article.sentence_stream(limit = TRAINING_SET, skip = TEST_SET)
word_tag_stream = IFD_Tagset.word_tag_stream(sentence_stream)
tnt_tagger.train(word_tag_stream)
with timeit(f"Train TnT tagger on IFD training set"):
# Get a sentence stream from parsed articles
# Number of sentences, size of training set
sample_ratio = 50
word_tag_stream = IFD_Corpus().word_tag_stream(skip = lambda n: n % sample_ratio == 0)
tnt_tagger.train(word_tag_stream)
with timeit(f"Store TnT model trained on {tnt_tagger.count} sentences"):
tnt_tagger.store(_TNT_MODEL_FILE)
if __name__ == "__main__":
print("Welcome to the Greynir POS tagging trainer\n")
try:
# Read configuration file
Settings.read(os.path.join(basepath, "config", "Reynir.conf"))
except ConfigError as e:
print("Configuration error: {0}".format(e))
quit()
# This is always run as a main program
try:
with timeit("Training session"):
train_tagger()
finally:
BIN_Db.cleanup()
示例9: page_not_found
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
@app.errorhandler(404)
def page_not_found(e):
""" Return a custom 404 error """
return 'Þessi vefslóð er ekki rétt', 404
@app.errorhandler(500)
def server_error(e):
""" Return a custom 500 error """
return 'Eftirfarandi villa kom upp: {}'.format(e), 500
# Initialize the main module
try:
# Read configuration file
Settings.read("Reynir.conf")
except ConfigError as e:
print("Configuration error: {0}".format(e))
quit()
if Settings.DEBUG:
print("Running Reynir with debug={0}, host={1}, db_hostname={2}"
.format(Settings.DEBUG, Settings.HOST, Settings.DB_HOSTNAME))
if __name__ == "__main__":
# Run a default Flask web server for testing if invoked directly as a main program
# Additional files that should cause a reload of the web server application
# Note: Reynir.grammar is automatically reloaded if its timestamp changes
示例10: Pipeline
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
class Pipeline():
def __init__( self, feature_engineer=None, model=None ):
# configure logging
self.logger = logging.getLogger("Pipeline")
handler = logging.FileHandler(settings.LOG_PATH)
handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s %(name)s: %(message)s'))
self.logger.addHandler(handler)
self.logger.setLevel(logging.DEBUG)
self.settings = Settings()
self.feature_engineer = FeatureEngineer( self.settings )
self.model = Model().get_model( Settings() )
def read( self, file_path ):
self.settings.read( file_path )
self.read_feature_engineer( settings.feature_engineer_path )
self.read_model( settings.model_path )
def read_feature_engineer( self, file_path ):
print('implement this')
def read_model( self, file_path ):
self.model = joblib.load( file_path+'_main.pkl' )
self.model.load_model(file_path)
def write( self, file_path ):
self.settings.write( file_path )
self.write_feature_engineer( settings.feature_engineer_path )
self.write_model( settings.model_path )
def write_feature_engineer( self, file_path ):
print('implement this')
def write_model( self, file_path ):
joblib.dump( self.model, file_path+'_main.pkl' )
self.model.store_model(file_path)
def set_feature_engineer( self, feature_engineer ):
self.feature_engineer = feature_engineer
def set_model( self, model ):
self.model = model
def train( self ):
# Create a "local" train and testset
initial_preparation.create_test_and_train_set()
# Feature engineer ( Transform features and create new ones )
self.logger.info('Start Feature Engineering')
train_data = self.feature_engineer.engineer_features(settings.LOKAL_TRAIN, settings.PROCESSED_TRAIN)
self.feature_engineer.train_state = False
test_data = self.feature_engineer.engineer_features (settings.LOKAL_TEST, settings.PROCESSED_TEST )
# Train model and evaluate
self.logger.info('Train and Evaluate Model')
score = self.model.train_model()
self.model.store_model()
self.logger.info('Model Score is %f', score)
def predict( self ):
# Feature engineer ( Transform features and create new ones )
self.logger.info('Start Feature Engineering')
self.feature_engineer.train_state = False
test_data = self.feature_engineer.engineer_features( settings.GLOBAL_TEST, settings.PROCESSED_GLOBAL )
#test_data.drop( settings.ID_FIELD, inplace=True, axis=1 )
# Train model and evaluate
self.logger.info('Train and Evaluate Model')
self.model.load_model()
ids, prediction = self.model.predict_submission()
submission_writer.create_submission( ids, prediction )
示例11: _main
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
def _main(argv=None):
""" Guido van Rossum's pattern for a Python main function """
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(
argv[1:],
"hifl:u:p:t:w:",
[
"help",
"init",
"force",
"update",
"limit=",
"url=",
"processor=",
"title=",
"workers=",
],
)
except getopt.error as msg:
raise Usage(msg)
limit = 10 # Default number of articles to parse, unless otherwise specified
init = False
url = None
force = False
update = False
title = None # Title pattern
proc = None # Single processor to invoke
num_workers = None # Number of workers to run simultaneously
# Process options
for o, a in opts:
if o in ("-h", "--help"):
print(__doc__)
return 0
elif o in ("-i", "--init"):
init = True
elif o in ("-f", "--force"):
force = True
elif o == "--update":
update = True
elif o in ("-l", "--limit"):
# Maximum number of articles to parse
try:
limit = int(a)
except ValueError as e:
pass
elif o in ("-u", "--url"):
# Single URL to process
url = a
elif o in ("-t", "--title"):
# Title pattern to match
title = a
elif o in ("-p", "--processor"):
# Single processor to invoke
proc = a
# In the case of a single processor, we force processing
# of already processed articles instead of processing new ones
force = True
elif o in ("-w", "--workers"):
# Limit the number of workers
num_workers = int(a) if int(a) else None
# Process arguments
for arg in args:
pass
if init:
# Initialize the scraper database
init_db()
else:
# Read the configuration settings file
try:
Settings.read("config/Reynir.conf")
# Don't run the processor in debug mode
Settings.DEBUG = False
except ConfigError as e:
print("Configuration error: {0}".format(e), file=sys.stderr)
return 2
if url:
# Process a single URL
process_article(url, processor=proc)
else:
# Process already parsed trees, starting on March 1, 2016
if force:
# --force overrides --update
update = False
if title:
# --title overrides both --force and --update
force = False
update = False
from_date = None if update else datetime(year=2016, month=3, day=1)
process_articles(
from_date=from_date,
limit=limit,
#.........这里部分代码省略.........
示例12: main
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
def main(argv=None):
""" Guido van Rossum's pattern for a Python main function """
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(
argv[1:], "hirl:u:", ["help", "init", "reparse", "limit=", "urls="]
)
except getopt.error as msg:
raise Usage(msg)
init = False
# !!! DEBUG default limit on number of articles to parse, unless otherwise specified
limit = 10
reparse = False
urls = None
# Process options
for o, a in opts:
if o in ("-h", "--help"):
print(__doc__)
sys.exit(0)
elif o in ("-i", "--init"):
init = True
elif o in ("-r", "--reparse"):
reparse = True
elif o in ("-l", "--limit"):
# Maximum number of articles to parse
try:
limit = int(a)
except ValueError:
pass
elif o in ("-u", "--urls"):
urls = a # Text file with list of URLs
# Process arguments
for _ in args:
pass
# Set logging format
logging.basicConfig(
format="%(asctime)s %(levelname)s:%(message)s", level=logging.INFO
)
# Read the configuration settings file
try:
Settings.read("config/Reynir.conf")
# Don't run the scraper in debug mode
Settings.DEBUG = False
except ConfigError as e:
print("Configuration error: {0}".format(e), file=sys.stderr)
return 2
if init:
# Initialize the scraper database
init_roots()
else:
# Run the scraper
scrape_articles(reparse=reparse, limit=limit, urls=urls)
except Usage as err:
print(err.msg, file=sys.stderr)
print("For help use --help", file=sys.stderr)
return 2
finally:
SessionContext.cleanup()
Article.cleanup()
# Completed with no error
return 0
示例13: Copyright
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
Copyright (c) 2016 Vilhjalmur Thorsteinsson
All rights reserved
See the accompanying README.md file for further licensing and copyright information.
This module is written in Python 3
"""
from settings import Settings, ConfigError
from db import SessionContext
from db.models import Person
from bindb import BIN_Db
try:
# Read configuration file
Settings.read("config/Reynir.conf")
except ConfigError as e:
print("Configuration error: {0}".format(e))
quit()
with SessionContext(commit = True) as session, BIN_Db.get_db() as bdb:
# Iterate through the persons
q = session.query(Person) \
.filter((Person.gender == None) | (Person.gender == 'hk')) \
.order_by(Person.name) \
.yield_per(200)
lastname = ""
for p in q:
示例14: print
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
import os
import sys
import argparse
import sip
sip.setapi("QString", 2)
sip.setapi("QVariant", 2)
from PyQt4.QtGui import QApplication
from mainui import MainUi
from settings import Settings
try:
use_lock = Settings.read()["options"]["use_lock"]
except KeyError:
use_lock = False
if(use_lock):
import fcntl
LOCK_FILE = os.path.join(Settings.settings_path, "simpleshortcuts.lock")
print("Using lock file:", LOCK_FILE)
f = open(LOCK_FILE, "w")
try:
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError as err:
if(err.errno == 11):
print("There is another instance running. Exiting...")
示例15: __init__
# 需要导入模块: from settings import Settings [as 别名]
# 或者: from settings.Settings import read [as 别名]
def __init__(self, *args):
super(QtGui.QDialog, self).__init__(*args)
ui_path = os.path.join(
os.path.dirname(__file__),
"settingsdialogui.ui"
)
uic.loadUi(ui_path, self)
self.name_edit.setDisabled(True)
self.command_edit.setDisabled(True)
self.icon_button.setDisabled(True)
self.move_up_button.setIcon(get_qicon("go-up"))
self.move_down_button.setIcon(get_qicon("go-down"))
self.add_button.setIcon(get_qicon("list-add"))
self.delete_button.setIcon(get_qicon("list-remove"))
self.drop_zone = DropZone()
self.drop_zone.setMinimumHeight(100)
self.drop_zone.setText("Drag and drop your desktop shortcut here to use it in this application.")
self.options_layout.addWidget(self.drop_zone)
validator = QtGui.QRegExpValidator(QtCore.QRegExp("[^&]*"))
self.name_edit.setValidator(validator)
for edit in (self.row1_edit, self.row2_edit, self.row3_edit):
validator = QtGui.QRegExpValidator(QtCore.QRegExp("[^ ]*"))
edit.setValidator(validator)
self.settings = Settings.read()
try:
self.options = self.settings["options"]
except KeyError:
self.options = {}
self.settings["options"] = self.options
try:
self.shortcuts = self.settings["shortcuts"]
except KeyError:
self.shortcuts = []
self.settings["shortcuts"] = self.shortcuts
self.icon_size_spinbox.setValue(self.options.get("icon_size", 48))
self.column_count_spinbox.setValue(self.options.get("column_count", 3))
self.column_width_spinbox.setValue(self.options.get("column_width", 230))
self.show_names_checkbox.setChecked(self.options.get("show_names", True))
self.show_hints_checkbox.setChecked(self.options.get("show_hints", True))
self.use_lock_checkbox.setChecked(self.options.get("use_lock", False))
self.row1_edit.setText(self.options.get("row1_keys", "QWERTY"))
self.row2_edit.setText(self.options.get("row2_keys", "ASDFGH"))
self.row3_edit.setText(self.options.get("row3_keys", "ZXCVBN"))
self.value_edited()
self.refresh_shortcuts()
self.shortcuts_listwidget.currentRowChanged.connect(self.selected_shortcut_changed)
self.add_button.clicked.connect(self.add_button_clicked)
self.delete_button.clicked.connect(self.delete_button_clicked)
self.move_up_button.clicked.connect(self.move_up_button_clicked)
self.move_down_button.clicked.connect(self.move_down_button_clicked)
self.icon_size_spinbox.valueChanged.connect(self.value_edited)
self.column_count_spinbox.valueChanged.connect(self.value_edited)
self.column_width_spinbox.valueChanged.connect(self.value_edited)
self.show_names_checkbox.stateChanged.connect(self.value_edited)
self.show_hints_checkbox.stateChanged.connect(self.value_edited)
self.use_lock_checkbox.stateChanged.connect(self.value_edited)
self.row1_edit.textEdited.connect(self.value_edited)
self.row2_edit.textEdited.connect(self.value_edited)
self.row3_edit.textEdited.connect(self.value_edited)
self.name_edit.textEdited.connect(self.value_edited)
self.command_edit.textEdited.connect(self.value_edited)
self.drop_zone.dropped.connect(self.shortcut_dropped)
self.icon_button.clicked.connect(self.icon_button_clicked)