本文整理汇总了Python中b3.getAbsolutePath函数的典型用法代码示例。如果您正苦于以下问题:Python getAbsolutePath函数的具体用法?Python getAbsolutePath怎么用?Python getAbsolutePath使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getAbsolutePath函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
def run(config=None):
if config:
config = b3.getAbsolutePath(config)
else:
# search for the config file
config = None
for p in (
"b3.xml",
"conf/b3.xml",
"b3/conf/b3.xml",
"~/b3.xml",
"~/conf/b3.xml",
"~/b3/conf/b3.xml",
"@b3/conf/b3.xml",
):
path = b3.getAbsolutePath(p)
print "Searching for config file: %s" % path
if os.path.isfile(path):
config = path
break
if not config:
Setup(config)
# raise SystemExit('Could not find config file.')
b3.start(config)
示例2: __init__
def __init__(self, config=None):
"""
Object constructor.
:param config: The B3 configuration file path
"""
if config:
# use the specified configuration file
config = b3.getAbsolutePath(config, True)
if not os.path.isfile(config):
console_exit('ERROR: configuration file not found (%s).\n'
'Please visit %s to create one.' % (config, B3_CONFIG_GENERATOR))
else:
# search a configuration file
for p in ('b3.%s', 'conf/b3.%s', 'b3/conf/b3.%s',
os.path.join(HOMEDIR, 'b3.%s'), os.path.join(HOMEDIR, 'conf', 'b3.%s'),
os.path.join(HOMEDIR, 'b3', 'conf', 'b3.%s'), '@b3/conf/b3.%s'):
for e in ('ini', 'cfg', 'xml'):
path = b3.getAbsolutePath(p % e, True)
if os.path.isfile(path):
print "Using configuration file: %s" % path
config = path
sleep(3)
break
if not config:
console_exit('ERROR: could not find any valid configuration file.\n'
'Please visit %s to create one.' % B3_CONFIG_GENERATOR)
try:
self.config = b3.config.MainConfig(b3.config.load(config))
if self.config.analyze():
raise b3.config.ConfigFileNotValid
except b3.config.ConfigFileNotValid:
console_exit('ERROR: configuration file not valid (%s).\n'
'Please visit %s to generate a new one.' % (config, B3_CONFIG_GENERATOR))
示例3: run_console
def run_console(options):
"""
Run B3 in console mode.
:param options: command line options
"""
analysis = None # main config analysis result
printexit = False # whether the exit message has been printed alreadty or not
try:
if options.config:
config = b3.getAbsolutePath(options.config, True)
if not os.path.isfile(config):
printexit = True
console_exit('ERROR: configuration file not found (%s).\n'
'Please visit %s to create one.' % (config, B3_CONFIG_GENERATOR))
else:
config = None
for p in ('b3.%s', 'conf/b3.%s', 'b3/conf/b3.%s',
os.path.join(HOMEDIR, 'b3.%s'), os.path.join(HOMEDIR, 'conf', 'b3.%s'),
os.path.join(HOMEDIR, 'b3', 'conf', 'b3.%s'), '@b3/conf/b3.%s'):
for e in ('ini', 'cfg', 'xml'):
path = b3.getAbsolutePath(p % e, True)
if os.path.isfile(path):
print "Using configuration file: %s" % path
config = path
sleep(3)
break
if not config:
printexit = True
console_exit('ERROR: could not find any valid configuration file.\n'
'Please visit %s to create one.' % B3_CONFIG_GENERATOR)
# LOADING MAIN CONFIGURATION
main_config = b3.config.MainConfig(b3.config.load(config))
analysis = main_config.analyze()
if analysis:
raise b3.config.ConfigFileNotValid('invalid configuration file specified')
# START B3
b3.start(main_config, options)
except b3.config.ConfigFileNotValid:
if analysis:
print 'CRITICAL: invalid configuration file specified:\n'
for problem in analysis:
print" >>> %s\n" % problem
else:
print 'CRITICAL: invalid configuration file specified!'
raise SystemExit(1)
except SystemExit, msg:
if not printexit and main_is_frozen():
if sys.stdout != sys.__stdout__:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
print msg
raw_input("press any key to continue...")
raise
示例4: init
def init(self, config_content=None):
""" load plugin config and initialise the plugin """
if config_content:
self.conf.loadFromString(config_content)
else:
if os.path.isfile(b3.getAbsolutePath('@b3/conf/plugin_chatlogger.ini')):
self.conf.load(b3.getAbsolutePath('@b3/conf/plugin_chatlogger.ini'))
else:
raise unittest.SkipTest("default config file '%s' does not exists" % b3.getAbsolutePath('@b3/conf/plugin_chatlogger.ini'))
self.p.onLoadConfig()
self.p.onStartup()
示例5: test_nominal
def test_nominal(self):
# GIVEN
existing_file_path = b3.getAbsolutePath('/a/file/that/exists')
when(os.path).isfile(existing_file_path).thenReturn(True)
self.conf.loadFromString(dedent(r"""
[settings]
private_key_file: /a/file/that/exists
"""))
# WHEN
self.p.onLoadConfig()
# THEN
self.assertIsNotNone(self.p.private_key_file)
self.assertEqual(existing_file_path, b3.getAbsolutePath(self.p.private_key_file))
示例6: getpath
def getpath(self, section, setting):
"""
Return an absolute path name and expand the user prefix (~).
:param section: The configuration file section.
:param setting: The configuration file setting.
"""
return b3.getAbsolutePath(self.get(section, setting), decode=True)
示例7: queryFromFile
def queryFromFile(self, fp, silent=False):
"""
This method executes an external sql file on the current database.
:param fp: The filepath of the file containing the SQL statements.
:param silent: Whether or not to silence MySQL warnings.
:raise Exception: If the query cannot be evaluated or if the given path cannot be resolved.
"""
# use existing connection or create a new one
# duplicate code of query() method which is needed not to spam the database
# with useless connection attempts (one for each query in the SQL file)
connection = self.getConnection()
if not connection:
raise Exception('lost connection with the storage layer during query')
# save standard error output
orig_stderr = sys.stderr
if silent:
# silence mysql warnings and such
sys.stderr = open(os.devnull, 'w')
path = b3.getAbsolutePath(fp)
if not os.path.exists(path):
raise Exception('SQL file does not exist: %s' % path)
with open(path, 'r') as sqlfile:
statements = self.getQueriesFromFile(sqlfile)
for stmt in statements:
# will stop if a single query generate an exception
self.query(stmt)
# reset standard error output
sys.stderr = orig_stderr
示例8: onStartup
def onStartup(self):
"""
Initialize plugin settings
"""
self.adminPlugin = self.console.getPlugin('admin')
if not self.adminPlugin:
raise AttributeError('could not find admin plugin')
# create database tables (if needed)
if 'nicks' not in self.console.storage.getTables():
sql_path_main = b3.getAbsolutePath('@b3/plugins/nickreg/sql')
sql_path = os.path.join(sql_path_main, self.console.storage.dsnDict['protocol'], 'nickreg.sql')
self.console.storage.queryFromFile(sql_path)
# register our commands
self.adminPlugin.registerCommand(self, 'registernick', self.min_level, self.cmd_regnick, 'regnick')
self.adminPlugin.registerCommand(self, 'deletenick', self.min_level, self.cmd_delnick, 'delnick')
self.adminPlugin.registerCommand(self, 'listnick', self.min_level, self.cmd_listnick)
# register our events
self.registerEvent('EVT_CLIENT_NAME_CHANGE', self.on_client_name_change)
self.registerEvent('EVT_GAME_MAP_CHANGE', self.on_map_change)
# install crontab
self.crontab = b3.cron.PluginCronTab(self, self.execute_crontab, '*/%s' % self.interval)
self.console.cron + self.crontab
示例9: onStartup
def onStartup(self):
"""
Initialize plugin settings.
"""
self.adminPlugin = self.console.getPlugin('admin')
# create database tables (if needed)
if 'callvote' not in self.console.storage.getTables():
sql_path_main = b3.getAbsolutePath('@b3/plugins/callvote/sql')
sql_path = os.path.join(sql_path_main, self.console.storage.dsnDict['protocol'], 'callvote.sql')
self.console.storage.queryFromFile(sql_path)
# unregister the veto command of the admin plugin
if self.console.getPlugin('poweradminurt'):
self.adminPlugin.unregisterCommand('paveto')
# register our commands
if 'commands' in self.config.sections():
for cmd in self.config.options('commands'):
level = self.config.get('commands', cmd)
sp = cmd.split('-')
alias = None
if len(sp) == 2:
cmd, alias = sp
func = getCmd(self, cmd)
if func:
self.adminPlugin.registerCommand(self, cmd, level, func, alias)
self.registerEvent('EVT_CLIENT_CALLVOTE', self.onCallvote)
self.registerEvent('EVT_VOTE_PASSED', self.onCallvoteFinish)
self.registerEvent('EVT_VOTE_FAILED', self.onCallvoteFinish)
# notice plugin started
self.debug('plugin started')
示例10: setUp
def setUp(self):
B3TestCase.setUp(self)
self.console.gameName = 'f00'
self.adminPlugin = AdminPlugin(self.console, '@b3/conf/plugin_admin.ini')
when(self.console).getPlugin("admin").thenReturn(self.adminPlugin)
self.adminPlugin.onLoadConfig()
self.adminPlugin.onStartup()
self.conf = CfgConfigParser()
self.conf.loadFromString(dedent(r"""
[commands]
plugin: superadmin
"""))
self.p = PluginmanagerPlugin(self.console, self.conf)
when(self.console).getPlugin("pluginmanager").thenReturn(self.adminPlugin)
self.p.onLoadConfig()
self.p.onStartup()
when(self.console.config).get_external_plugins_dir().thenReturn(b3.getAbsolutePath('@b3\\extplugins'))
# store them also in the console _plugins dict
self.console._plugins['admin'] = self.adminPlugin
self.console._plugins['pluginmanager'] = self.p
示例11: test_no_generic_or_default_warn_reason
def test_no_generic_or_default_warn_reason(self):
# load the default plugin_admin.ini file after having remove the 'generic' setting from section 'warn_reasons'
new_config_content = ""
with open(b3.getAbsolutePath('@b3/conf/plugin_admin.ini')) as config_file:
is_in_warn_reasons_section = False
for line in config_file:
if line == '[warn_reasons]':
is_in_warn_reasons_section = True
if not is_in_warn_reasons_section:
new_config_content += (line + '\n')
else:
if line.startswith('['):
new_config_content += (line + '\n')
is_in_warn_reasons_section = False
else:
if line.startswith("generic") or line.startswith("default"):
pass
else:
new_config_content += (line + '\n')
self.init(new_config_content)
self.joe.message = Mock(lambda x: sys.stdout.write("message to Joe: " + x + "\n"))
self.joe.connects(0)
self.joe.says('!warntest')
self.joe.message.assert_called_once_with('^2TEST: ^1WARNING^7 [^31^7]: ^7behave yourself')
self.joe.message.reset_mock()
self.joe.says('!warntest argue')
self.joe.message.assert_called_once_with('^2TEST: ^1WARNING^7 [^31^7]: ^3Rule #3: No arguing with admins (listen and learn or leave)')
示例12: setUp
def setUp(self):
super(Test_Tk_default_config, self).setUp()
self.console.gameName = 'f00'
self.conf = CfgConfigParser()
self.conf.load(b3.getAbsolutePath('@b3/conf/plugin_tk.ini'))
self.p = TkPlugin(self.console, self.conf)
self.p.onLoadConfig()
示例13: connect
def connect(self):
"""
Establish and return a connection with the storage layer.
Will store the connection object also in the 'db' attribute so in the future we can reuse it.
:return The connection instance if established successfully, otherwise None.
"""
# no need to catch ImportError since we already did that in __new__()
# do not retry too soon because the MySQL server could
# have connection troubles and we do not want to spam it
if time() - self._lastConnectAttempt < self._reconnectDelay:
self.db = None
self.console.bot('New PostgreSQL database connection requested but last connection attempt '
'failed less than %s seconds ago: exiting...' % self._reconnectDelay)
else:
# close the active connection (if any)
self.shutdown()
self.console.bot('Connecting to PostgreSQL database: %(protocol)s://%(user)s:******@%(host)s:%(port)s%(path)s...', self.dsnDict)
try:
import psycopg2
self.db = psycopg2.connect(host=self.dsnDict['host'],
port=self.dsnDict['port'],
user=self.dsnDict['user'],
password=self.dsnDict['password'],
database=self.dsnDict['path'][1:])
self.db.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
self.db.set_client_encoding("UTF8")
self.console.bot('Successfully established a connection with PostgreSQL database')
self._lastConnectAttempt = 0
if self._consoleNotice:
self.console.screen.write('Connecting to DB : OK\n')
self._consoleNotice = False
# check whether the database is ready for usage or if we have to import B3 sql files to generate necessary
# tables: if database is empty, then then AdminPlugin will raise an exception upon loading hence B3 won't be
# operational. I placed the check here since it doesn't make sense to keep loading plugins if B3 will crash.
if not self.getTables():
try:
self.console.info("Missing PostgreSQL database tables: importing SQL file: %s..." % b3.getAbsolutePath("@b3/sql/postgresql/b3.sql"))
self.queryFromFile("@b3/sql/postgresql/b3.sql")
except Exception, e:
self.shutdown()
self.console.critical("Missing PostgreSQL database tables. You need to create the necessary tables for "
"B3 to work. You can do so by importing the following SQL script into your "
"database: %s. An attempt of creating tables automatically just failed: %s" %
(b3.getAbsolutePath("@b3/sql/postgresql/b3.sql"), e))
except Exception, e:
self.console.error('Database connection failed: working in remote mode: %s - %s', e, extract_tb(sys.exc_info()[2]))
self.db = None
self._lastConnectAttempt = time()
if self._consoleNotice:
self.console.screen.write('Connecting to DB : FAILED!\n')
self._consoleNotice = False
示例14: run
def run(config=None):
if config:
config = b3.getAbsolutePath(config)
else:
# search for the config file
config = None
for p in ('b3.xml', 'conf/b3.xml', 'b3/conf/b3.xml', '~/b3.xml', '~/conf/b3.xml', '~/b3/conf/b3.xml', '@b3/conf/b3.xml'):
path = b3.getAbsolutePath(p)
print 'Searching for config file: %s' % path
if os.path.isfile(path):
config = path
break
if not config:
raise SystemExit('Could not find config file.')
b3.start(config)
示例15: _search_config_file
def _search_config_file(match):
"""
Helper that returns a list of available configuration file paths for the given plugin.
:param match: The plugin name
"""
# first look in the built-in plugins directory
search = '%s%s*%s*' % (b3.getAbsolutePath('@b3\\conf'), os.path.sep, match)
self.debug('searching for configuration file(s) matching: %s' % search)
collection = glob.glob(search)
if len(collection) > 0:
return collection
# if none is found, then search in the extplugins directory
extplugins_dir = self.console.config.get_external_plugins_dir()
search = '%s%s*%s*' % (os.path.join(b3.getAbsolutePath(extplugins_dir), match, 'conf'), os.path.sep, match)
self.debug('searching for configuration file(s) matching: %s' % search)
collection = glob.glob(search)
return collection