getopt --> argparse, redid logging, code cleanup
This commit is contained in:
parent
45320c9bea
commit
ef0898e8c7
19 changed files with 221 additions and 344 deletions
|
@ -1,7 +1,7 @@
|
|||
# Changelog
|
||||
(This document uses YYYY-MM-DD)
|
||||
|
||||
## [v2.4.3] - 2022-09-05
|
||||
## [v2.4.3] - 2022-09-06
|
||||
|
||||
### Added
|
||||
- Support for color via IRCv3 metadata draft.
|
||||
|
@ -11,10 +11,16 @@
|
|||
### Changed
|
||||
- Reenabled server certificate validation when using SSL.
|
||||
- Uses the system's local certificates, so might fail on some installations.
|
||||
- Redid command-line handling with the argparse module instead of getopt.
|
||||
- Restructured imports & data directory checks in pesterchum.py
|
||||
|
||||
### Fixed
|
||||
- Error when setting quirk with PyQt5.
|
||||
|
||||
### Depreciated
|
||||
- Disabled the console for now since no one seems to use it and it caused an issue on import.
|
||||
- Logging.config/configparser logging configuration, not aware of anyone that actually used this. Logging level can still be specified with command line arguments. (-l --logging)
|
||||
|
||||
## [v2.4.2] - 2022-08-14
|
||||
|
||||
### Added
|
||||
|
|
|
@ -7,7 +7,6 @@ import traceback
|
|||
import time
|
||||
import datetime
|
||||
import logging
|
||||
import logging.config
|
||||
|
||||
try:
|
||||
from PyQt6 import QtCore, QtGui, QtWidgets
|
||||
|
@ -25,11 +24,8 @@ import ostools
|
|||
#from version import _pcVersion
|
||||
from pnc.dep.attrdict import AttrDict
|
||||
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
|
||||
class ConsoleWindow(QtWidgets.QDialog):
|
||||
#~class ConsoleWindow(styler.PesterBaseWindow):
|
||||
# A simple console class, cobbled together from the corpse of another.
|
||||
|
|
10
convo.py
10
convo.py
|
@ -1,6 +1,5 @@
|
|||
import sys
|
||||
import logging
|
||||
import logging.config
|
||||
from string import Template
|
||||
from time import strftime
|
||||
from datetime import datetime, timedelta
|
||||
|
@ -15,14 +14,15 @@ except ImportError:
|
|||
|
||||
import ostools
|
||||
from dataobjs import PesterHistory
|
||||
from parsetools import (convertTags, lexMessage, mecmd, colorBegin, colorEnd,
|
||||
from parsetools import (convertTags,
|
||||
lexMessage,
|
||||
mecmd,
|
||||
colorBegin,
|
||||
colorEnd,
|
||||
smiledict)
|
||||
import parsetools
|
||||
from pnc.dep.attrdict import AttrDict
|
||||
|
||||
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
class PesterTabWindow(QtWidgets.QFrame):
|
||||
|
|
|
@ -1,8 +1,5 @@
|
|||
import logging
|
||||
import logging.config
|
||||
import ostools
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
try:
|
||||
from PyQt6 import QtGui
|
||||
|
|
3
irc.py
3
irc.py
|
@ -1,5 +1,4 @@
|
|||
import logging
|
||||
import logging.config
|
||||
import socket
|
||||
import random
|
||||
import time
|
||||
|
@ -22,8 +21,6 @@ from oyoyo.client import IRCClient
|
|||
from oyoyo.cmdhandler import DefaultCommandHandler
|
||||
from oyoyo import helpers, services
|
||||
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
# Python 3
|
||||
|
|
|
@ -5,7 +5,6 @@ Hard for me to work on this since I know absolutely nothing about lua, plus I'm
|
|||
+ I asked and there doesn't seem to be a single person who actually used this 💀
|
||||
|
||||
import logging
|
||||
import logging.config
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
|
@ -15,8 +14,6 @@ from PyQt6 import QtCore, QtGui, QtWidgets
|
|||
import ostools
|
||||
from quirks import ScriptQuirks
|
||||
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
try:
|
||||
|
|
4
memos.py
4
memos.py
|
@ -1,5 +1,4 @@
|
|||
import logging
|
||||
import logging.config
|
||||
import re
|
||||
from string import Template
|
||||
from datetime import timedelta, datetime
|
||||
|
@ -21,8 +20,6 @@ from parsetools import (convertTags, timeProtocol, lexMessage, colorBegin,
|
|||
mecmd, smiledict)
|
||||
from logviewer import PesterLogViewer
|
||||
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
# Python 3
|
||||
|
@ -412,7 +409,6 @@ class PesterMemo(PesterConvo):
|
|||
|
||||
self.textArea = MemoText(self.mainwindow.theme, self)
|
||||
self.textInput = MemoInput(self.mainwindow.theme, self)
|
||||
print(self.textInput)
|
||||
self.textInput.setFocus()
|
||||
|
||||
self.miniUserlist = QtWidgets.QPushButton(">\n>", self)
|
||||
|
|
24
ostools.py
24
ostools.py
|
@ -32,6 +32,27 @@ def osVer():
|
|||
elif isLinux():
|
||||
return " ".join(platform.linux_distribution())
|
||||
|
||||
def validateDataDir():
|
||||
"""Checks if data directory is present"""
|
||||
# Define paths
|
||||
datadir = getDataDir()
|
||||
profile = os.path.join(datadir, "profiles")
|
||||
quirks = os.path.join(datadir, "quirks")
|
||||
logs = os.path.join(datadir, "logs")
|
||||
errorlogs = os.path.join(datadir, "errorlogs")
|
||||
backup = os.path.join(datadir, "backup")
|
||||
js_pchum = os.path.join(datadir, "pesterchum.js")
|
||||
|
||||
dirs = [datadir, profile, quirks, logs, errorlogs, backup]
|
||||
for d in dirs:
|
||||
if (os.path.isdir(d) == False) or (os.path.exists(d) == False):
|
||||
os.makedirs(d, exist_ok=True)
|
||||
|
||||
# pesterchum.js
|
||||
if not os.path.exists(js_pchum):
|
||||
with open(js_pchum, 'w') as f:
|
||||
f.write("{}")
|
||||
|
||||
def getDataDir():
|
||||
# Temporary fix for non-ascii usernames
|
||||
# If username has non-ascii characters, just store userdata
|
||||
|
@ -43,5 +64,6 @@ def getDataDir():
|
|||
return os.path.join(QStandardPaths.writableLocation(QStandardPaths.StandardLocation.HomeLocation), ".pesterchum/")
|
||||
else:
|
||||
return os.path.join(QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppLocalDataLocation), "pesterchum/")
|
||||
except UnicodeDecodeError:
|
||||
except UnicodeDecodeError as e:
|
||||
print(e)
|
||||
return ''
|
||||
|
|
|
@ -16,10 +16,6 @@
|
|||
# THE SOFTWARE.
|
||||
|
||||
import logging
|
||||
import logging.config
|
||||
import ostools
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
import logging
|
||||
|
@ -326,7 +322,7 @@ class IRCClient:
|
|||
|
||||
for el in data:
|
||||
tags, prefix, command, args = parse_raw_irc_command(el)
|
||||
print(tags, prefix, command, args)
|
||||
#print(tags, prefix, command, args)
|
||||
try:
|
||||
# Only need tags with tagmsg
|
||||
if command.upper() == "TAGMSG":
|
||||
|
|
|
@ -15,18 +15,13 @@
|
|||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
# THE SOFTWARE.
|
||||
import logging
|
||||
import logging.config
|
||||
import ostools
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
import inspect
|
||||
import logging
|
||||
|
||||
from oyoyo import helpers
|
||||
from oyoyo.parse import parse_nick
|
||||
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
def protected(func):
|
||||
""" decorator to protect functions from being called """
|
||||
func.protected = True
|
||||
|
|
|
@ -18,13 +18,10 @@
|
|||
""" contains helper functions for common irc commands """
|
||||
|
||||
import logging
|
||||
import logging.config
|
||||
import ostools
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
import random
|
||||
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
def msg(cli, user, msg):
|
||||
for line in msg.split('\n'):
|
||||
cli.send("PRIVMSG", user, ":%s" % line)
|
||||
|
|
|
@ -16,13 +16,9 @@
|
|||
# THE SOFTWARE.
|
||||
|
||||
import logging
|
||||
import logging.config
|
||||
|
||||
import ostools
|
||||
from oyoyo.ircevents import numeric_events
|
||||
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
def parse_raw_irc_command(element):
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
import logging
|
||||
import logging.config
|
||||
import re
|
||||
import collections
|
||||
from copy import copy
|
||||
|
@ -20,8 +19,6 @@ from quirks import ScriptQuirks
|
|||
from pyquirks import PythonQuirks
|
||||
#from luaquirks import LuaQuirks
|
||||
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
# I'll clean up the things that are no longer needed once the transition is
|
||||
|
@ -42,16 +39,18 @@ _oocre = re.compile(r"([\[(\{])\1.*([\])\}])\2")
|
|||
_format_begin = re.compile(r'(?i)<([ibu])>')
|
||||
_format_end = re.compile(r'(?i)</([ibu])>')
|
||||
_honk = re.compile(r"(?i)\bhonk\b")
|
||||
_groupre = re.compile(r"\\([0-9]+)")
|
||||
|
||||
quirkloader = ScriptQuirks()
|
||||
_functionre = None
|
||||
|
||||
def loadQuirks():
|
||||
global quirkloader, _functionre
|
||||
quirkloader.add(PythonQuirks())
|
||||
#quirkloader.add(LuaQuirks())
|
||||
quirkloader.loadAll()
|
||||
# Quirks are already listed in quirks.py, so logging is redundant here.
|
||||
#PchumLog.debug(quirkloader.funcre())
|
||||
quirkloader.funcre()
|
||||
_functionre = re.compile(r"%s" % quirkloader.funcre())
|
||||
_groupre = re.compile(r"\\([0-9]+)")
|
||||
|
||||
def reloadQuirkFunctions():
|
||||
quirkloader.loadAll()
|
||||
|
|
341
pesterchum.py
341
pesterchum.py
|
@ -1,41 +1,60 @@
|
|||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import os
|
||||
import sys
|
||||
import shutil
|
||||
import getopt
|
||||
import configparser
|
||||
import argparse
|
||||
import traceback
|
||||
|
||||
# Python 3
|
||||
QString = str
|
||||
|
||||
if os.path.dirname(sys.argv[0]):
|
||||
os.chdir(os.path.dirname(sys.argv[0]))
|
||||
print("Usage: pesterchum.py [OPTIONS]")
|
||||
print("Use -h/--help to see the available options."
|
||||
"\nLogging is configured in logging.ini")
|
||||
# Help
|
||||
if ('--help' in sys.argv[1:]) or ('-h' in sys.argv[1:]):
|
||||
print("Possible arguments:")
|
||||
help_arguments = (" -l, --logging\n Specify level of logging, possible values are:\n"
|
||||
" CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET.\n"
|
||||
" The default value is WARNING.\n"
|
||||
" (See https://docs.python.org/3/library/logging.html)\n\n"
|
||||
" -s, --server\n Specify server override. (legacy)\n\n"
|
||||
" -p, --port\n Specify port override. (legacy)\n\n"
|
||||
" --advanced\n Enable advanced.\n\n"
|
||||
" --no-honk\n Disable honking.\n")
|
||||
print(help_arguments)
|
||||
sys.exit()
|
||||
|
||||
import logging
|
||||
import logging.config
|
||||
import datetime
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
import json
|
||||
|
||||
import ostools
|
||||
import nickservmsgs
|
||||
import pytwmn
|
||||
#import console
|
||||
from pnc.dep.attrdict import AttrDict
|
||||
from profile import (userConfig,
|
||||
userProfile,
|
||||
pesterTheme,
|
||||
PesterLog,
|
||||
PesterProfileDB)
|
||||
from menus import (PesterChooseQuirks,
|
||||
PesterChooseTheme,
|
||||
PesterChooseProfile,
|
||||
PesterOptions,
|
||||
PesterUserlist,
|
||||
PesterMemoList,
|
||||
LoadingScreen,
|
||||
AboutPesterchum,
|
||||
UpdatePesterchum,
|
||||
AddChumDialog)
|
||||
from mood import (Mood,
|
||||
PesterMoodAction,
|
||||
PesterMoodHandler,
|
||||
PesterMoodButton)
|
||||
from dataobjs import PesterProfile, pesterQuirk, pesterQuirks
|
||||
from generic import (PesterIcon,
|
||||
RightClickTree,
|
||||
PesterList,
|
||||
CaseInsensitiveDict,
|
||||
MovingWindow,
|
||||
NoneSound,
|
||||
WMButton)
|
||||
from convo import (PesterTabWindow,
|
||||
PesterConvo)
|
||||
from parsetools import (convertTags,
|
||||
addTimeInitial,
|
||||
themeChecker,
|
||||
ThemeException,
|
||||
loadQuirks)
|
||||
from memos import PesterMemo, MemoTabWindow, TimeTracker
|
||||
from irc import PesterIRC
|
||||
from logviewer import PesterLogUserSelect, PesterLogViewer
|
||||
from randomer import RandomHandler, RANDNICK
|
||||
from toast import PesterToastMachine, PesterToast
|
||||
|
||||
try:
|
||||
from PyQt6 import QtCore, QtGui, QtWidgets
|
||||
|
@ -45,199 +64,69 @@ except ImportError:
|
|||
from PyQt5 import QtCore, QtGui, QtWidgets
|
||||
from PyQt5.QtWidgets import QAction, QShortcut, QActionGroup
|
||||
|
||||
#vnum = QtCore.qVersion()
|
||||
#major = int(vnum[:vnum.find(".")])
|
||||
#if vnum.find(".", vnum.find(".")+1) != -1:
|
||||
# minor = int(vnum[vnum.find(".")+1:vnum.find(".", vnum.find(".")+1)])
|
||||
#else:
|
||||
# minor = int(vnum[vnum.find(".")+1:])
|
||||
#if (major < 6) or ((major > 6) and (minor < 2)):
|
||||
# print("ERROR: Pesterchum requires at least Qt version >= 6.2")
|
||||
# print("You currently have version " + str(vnum) + ". Please upgrade Qt.")
|
||||
# sys.exit()
|
||||
|
||||
import ostools
|
||||
# Placed here before importing the rest of pesterchum, since bits of it need
|
||||
# OSX's data directory and it doesn't hurt to have everything set up before
|
||||
# plowing on. :o)
|
||||
# ~Lex
|
||||
# Data directory
|
||||
ostools.validateDataDir()
|
||||
_datadir = ostools.getDataDir()
|
||||
if not os.path.isdir(_datadir):
|
||||
os.makedirs(_datadir)
|
||||
if not os.path.isdir(os.path.join(_datadir, 'errorlogs')):
|
||||
os.makedirs(os.path.join(_datadir, 'errorlogs'))
|
||||
# See, what I've done here is that _datadir is '' if we're not on OSX, so the
|
||||
# concatination is the same as if it wasn't there.
|
||||
# UPDATE 2011-11-28 <Kiooeht>:
|
||||
# Now using data directory as defined by QDesktopServices on all platforms
|
||||
# (on Linux, same as using xdg). To stay safe with older versions, copy any
|
||||
# data (profiles, logs, etc) from old location to new data directory.
|
||||
|
||||
config = configparser.ConfigParser()
|
||||
# Create logging.ini
|
||||
#if os.path.exists(_datadir + "logging.ini") == False:
|
||||
try:
|
||||
config.read(_datadir + 'logging.ini')
|
||||
# Data directory dependent actions
|
||||
loadQuirks()
|
||||
|
||||
# Test load
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
# Command line options
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--server",
|
||||
"-s",
|
||||
metavar="ADDRESS",
|
||||
help="Specify server override. (legacy)")
|
||||
parser.add_argument("--port",
|
||||
"-p",
|
||||
metavar="PORT",
|
||||
help="Specify port override. (legacy)")
|
||||
parser.add_argument("--logging",
|
||||
"-l",
|
||||
metavar="LEVEL",
|
||||
default="WARNING",
|
||||
help=("Specify level of logging, possible values are:"
|
||||
" CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET."
|
||||
" (https://docs.python.org/3/library/logging.html)"))
|
||||
parser.add_argument("--advanced",
|
||||
action="store_true",
|
||||
help=("Enable 'advanced' mode. Adds an 'advanced' tab"
|
||||
" to settings for setting user mode and adds"
|
||||
" channel modes in memo titles."
|
||||
" This feature is currently not maintained."))
|
||||
parser.add_argument("--nohonk",
|
||||
action="store_true",
|
||||
help="Disables the honk soundeffect 🤡📣")
|
||||
|
||||
# Set logging config section, log level is in oppts.
|
||||
# Logger
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
except:
|
||||
#config.read('logging.ini.example')
|
||||
config = configparser.ConfigParser()
|
||||
# Handlers
|
||||
file_handler = logging.FileHandler(os.path.join(_datadir, 'pesterchum.log'))
|
||||
stream_handler = logging.StreamHandler()
|
||||
# Format
|
||||
formatter = logging.Formatter('%(asctime)s - %(module)s - %(levelname)s - %(message)s')
|
||||
file_handler.setFormatter(formatter)
|
||||
stream_handler.setFormatter(formatter)
|
||||
# Add handlers
|
||||
PchumLog.addHandler(file_handler)
|
||||
PchumLog.addHandler(stream_handler)
|
||||
|
||||
# Default setup
|
||||
config['loggers'] = {'keys': 'root,pchumLogger'}
|
||||
config['handlers'] = {'keys': 'consoleHandler,FileHandler'}
|
||||
config['formatters'] = {'keys': 'simpleFormatter'}
|
||||
config['logger_root'] = {'level': 'WARNING',
|
||||
'handlers': 'consoleHandler'}
|
||||
config['handler_consoleHandler'] = {'class': 'StreamHandler',
|
||||
'level': 'WARNING',
|
||||
'formatter': 'simpleFormatter',
|
||||
'args': '(sys.stdout,)'}
|
||||
config['handler_FileHandler'] = {'class': 'FileHandler',
|
||||
'level': 'WARNING',
|
||||
'formatter': 'simpleFormatter'}
|
||||
config['logger_pchumLogger'] = {'level': 'WARNING',
|
||||
'handlers': 'consoleHandler,FileHandler',
|
||||
'qualname': 'pchumLogger',
|
||||
'propagate': '0'}
|
||||
config['formatter_simpleFormatter'] = {'format': '%(levelname)s - %(module)s - %(message)s',
|
||||
'datefmt': ''}
|
||||
|
||||
# Enable file logging
|
||||
config['handlers']['keys'] = 'consoleHandler,FileHandler'
|
||||
config['logger_pchumLogger']['handlers'] = 'consoleHandler,FileHandler'
|
||||
#(r'C:\Users\X\AppData\Local\pesterchum\pesterchum.log', 'a')
|
||||
config['handler_FileHandler'] = {'class': 'FileHandler',
|
||||
'level': 'WARNING',
|
||||
'formatter': 'simpleFormatter',
|
||||
'args': (_datadir + 'pesterchum.log', 'a')}
|
||||
|
||||
print(config.sections())
|
||||
|
||||
|
||||
loglevel = "30"# Warning (Default)
|
||||
if ('--logging' in sys.argv[1:]) or ('-l' in sys.argv[1:]) & (False == ('--logging' in sys.argv[1:]) and ('-l' in sys.argv[1:])):
|
||||
try:
|
||||
# If both are specified, this does not run.
|
||||
if ('-l' in sys.argv[1:]):
|
||||
loglevel = sys.argv[sys.argv.index('-l') + 1]
|
||||
if ('--logging' in sys.argv[1:]):
|
||||
loglevel = sys.argv[sys.argv.index('--logging') + 1]
|
||||
|
||||
loglevel = loglevel.upper().strip()
|
||||
|
||||
config.read(_datadir + 'logging.ini')
|
||||
|
||||
print("loglevel = " + loglevel)
|
||||
|
||||
if loglevel == "50" or loglevel == "CRITICAL":
|
||||
loglevel = "CRITICAL"
|
||||
print("Logging Level is CRITICAL")
|
||||
elif loglevel == "40" or loglevel == "ERROR":
|
||||
loglevel = "ERROR"
|
||||
print("Logging Level is ERROR")
|
||||
elif loglevel == "30" or loglevel == "WARNING":
|
||||
loglevel = "WARNING"
|
||||
print("Logging Level is WARNING")
|
||||
elif loglevel == "20" or loglevel == "INFO":
|
||||
loglevel = "INFO"
|
||||
print("Logging Level is INFO")
|
||||
elif loglevel == "10" or loglevel == "DEBUG":
|
||||
loglevel = "DEBUG"
|
||||
print("Logging Level is DEBUG")
|
||||
elif loglevel == "0" or loglevel == "NOTSET":
|
||||
loglevel = "NOTSET"
|
||||
print("Logging Level is NOTSET")
|
||||
else:
|
||||
loglevel = "WARNING"
|
||||
print("Logging Level is WARNING")
|
||||
|
||||
config['logger_root']['level'] = loglevel
|
||||
config['logger_pchumLogger']['level'] = loglevel
|
||||
config['handler_consoleHandler']['level'] = loglevel
|
||||
config['handler_FileHandler']['level'] = loglevel
|
||||
|
||||
# Remove from argv because the rest of the code can't handle it :/
|
||||
if ('-l' in sys.argv[1:]):
|
||||
sys.argv.pop(sys.argv.index('-l') + 1)
|
||||
sys.argv.pop(sys.argv.index('-l'))
|
||||
if ('--logging' in sys.argv[1:]):
|
||||
sys.argv.pop(sys.argv.index('--logging') + 1)
|
||||
sys.argv.pop(sys.argv.index('--logging'))
|
||||
except:
|
||||
logging.exception("Invalid syntax?")
|
||||
|
||||
# Update logging.ini
|
||||
with open(_datadir + "logging.ini", 'w') as configfile:
|
||||
config.write(configfile)
|
||||
|
||||
# Load logging.ini
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
try:
|
||||
import console
|
||||
_CONSOLE = True
|
||||
except ImportError:
|
||||
_CONSOLE = False
|
||||
logging.warning("Console file not shipped; skipping.")
|
||||
|
||||
if _datadir:
|
||||
if not os.path.exists(_datadir):
|
||||
os.makedirs(_datadir)
|
||||
if not os.path.exists(_datadir+"profiles/") and os.path.exists("profiles/"):
|
||||
shutil.move("profiles/", _datadir+"profiles/")
|
||||
if not os.path.exists(_datadir+"pesterchum.js") and os.path.exists("pesterchum.js"):
|
||||
shutil.move("pesterchum.js", _datadir+"pesterchum.js")
|
||||
if not os.path.exists(_datadir+"logs/") and os.path.exists("logs/"):
|
||||
shutil.move("logs/", _datadir+"logs/")
|
||||
|
||||
if not os.path.exists(_datadir+"profiles"):
|
||||
os.mkdir(_datadir+"profiles")
|
||||
if not os.path.exists(_datadir+"pesterchum.js"):
|
||||
f = open(_datadir+"pesterchum.js", 'w')
|
||||
f.write("{}")
|
||||
f.close()
|
||||
if not os.path.exists(_datadir+"logs"):
|
||||
os.mkdir(_datadir+"logs")
|
||||
|
||||
from profile import userConfig, userProfile, pesterTheme, PesterLog, \
|
||||
PesterProfileDB
|
||||
from menus import PesterChooseQuirks, PesterChooseTheme, \
|
||||
PesterChooseProfile, PesterOptions, PesterUserlist, PesterMemoList, \
|
||||
LoadingScreen, AboutPesterchum, UpdatePesterchum, AddChumDialog
|
||||
from mood import Mood, PesterMoodAction, PesterMoodHandler, PesterMoodButton
|
||||
from dataobjs import PesterProfile, pesterQuirk, pesterQuirks
|
||||
from generic import PesterIcon, RightClickTree, \
|
||||
PesterList, CaseInsensitiveDict, MovingWindow, \
|
||||
NoneSound, WMButton
|
||||
from convo import PesterTabWindow, PesterConvo
|
||||
from parsetools import convertTags, addTimeInitial, themeChecker, ThemeException
|
||||
from memos import PesterMemo, MemoTabWindow, TimeTracker
|
||||
from irc import PesterIRC
|
||||
from logviewer import PesterLogUserSelect, PesterLogViewer
|
||||
from randomer import RandomHandler, RANDNICK
|
||||
import nickservmsgs
|
||||
from toast import PesterToastMachine, PesterToast
|
||||
import pytwmn
|
||||
|
||||
#canon_handles = ["apocalypseArisen", "arsenicCatnip", "arachnidsGrip", "adiosToreador",
|
||||
# "caligulasAquarium", "cuttlefishCuller", "carcinoGeneticist", "centaursTesticle",
|
||||
# "grimAuxiliatrix", "gallowsCalibrator", "gardenGnostic", "ectoBiologist",
|
||||
# "twinArmageddons", "terminallyCapricious", "turntechGodhead", "tentacleTherapist"]
|
||||
# Global variables
|
||||
BOTNAMES = []
|
||||
CUSTOMBOTS = ["CALSPRITE", RANDNICK.upper()]
|
||||
SERVICES = ["NICKSERV", "CHANSERV", "MEMOSERV", "OPERSERV", "HELPSERV", "HOSTSERV", "BOTSERV"]
|
||||
BOTNAMES.extend(CUSTOMBOTS)
|
||||
BOTNAMES.extend(SERVICES)
|
||||
|
||||
# Save the main app. From here, we should be able to get everything else in
|
||||
# order, for console use.
|
||||
_CONSOLE = False
|
||||
_CONSOLE_ENV = AttrDict()
|
||||
_CONSOLE_ENV.PAPP = None
|
||||
# Python 3
|
||||
QString = str
|
||||
# Command line arguments
|
||||
_ARGUMENTS = parser.parse_args()
|
||||
|
||||
# Import audio module
|
||||
if ostools.isLinux():
|
||||
|
@ -250,7 +139,8 @@ if ostools.isLinux():
|
|||
import pygame
|
||||
except ImportError:
|
||||
print("Failed to import pygame, falling back to QtMultimedia. "
|
||||
+ "For QtMultimedia to work on Linux you need GStreamer"
|
||||
+ "This should also work fine, but for QtMultimedia to work "
|
||||
+ "on Linux you need GStreamer"
|
||||
+ " + a plugin for decoding the wave format.")
|
||||
try:
|
||||
from PyQt6 import QtMultimedia
|
||||
|
@ -1270,15 +1160,16 @@ class PesterWindow(MovingWindow):
|
|||
# This was almost certainly intentional.
|
||||
if "advanced" in options:
|
||||
self.advanced = options["advanced"]
|
||||
else: self.advanced = False
|
||||
else:
|
||||
self.advanced = False
|
||||
if "server" in options:
|
||||
self.serverOverride = options["server"]
|
||||
if "port" in options:
|
||||
self.portOverride = options["port"]
|
||||
if "honk" in options:
|
||||
self.honk = options["honk"]
|
||||
|
||||
else: self.honk = True
|
||||
else:
|
||||
self.honk = True
|
||||
self.modes = ""
|
||||
|
||||
self.sound_type = None
|
||||
|
@ -4116,19 +4007,27 @@ class MainProgram(QtCore.QObject):
|
|||
|
||||
def oppts(self, argv):
|
||||
options = {}
|
||||
# The parser and arguments are defined globally,
|
||||
# since --help causes Qt to raise an exception otherwise.
|
||||
args = _ARGUMENTS
|
||||
try:
|
||||
opts, args = getopt.getopt(argv, "s:p:", ["server=", "port=", "advanced", "no-honk"])
|
||||
except getopt.GetoptError:
|
||||
return options
|
||||
for opt, arg in opts:
|
||||
if opt in ("-s", "--server"):
|
||||
options["server"] = arg
|
||||
elif opt in ("-p", "--port"):
|
||||
options["port"] = arg
|
||||
elif opt in ("--advanced"):
|
||||
options["advanced"] = True
|
||||
elif opt in ("--no-honk"):
|
||||
if args.server != None:
|
||||
options["server"] = args.server
|
||||
if args.port != None:
|
||||
options["port"] = args.port
|
||||
# Set log level
|
||||
PchumLog.setLevel(args.logging.upper())
|
||||
file_handler.setLevel(args.logging.upper())
|
||||
stream_handler.setLevel(args.logging.upper())
|
||||
# Enable advanced
|
||||
options["advanced"] = args.advanced
|
||||
# Disable honks
|
||||
if args.nohonk == True:
|
||||
options["honk"] = False
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return options
|
||||
|
||||
return options
|
||||
|
||||
def uncaughtException(self, exc, value, tb):
|
||||
|
|
30
profile.py
30
profile.py
|
@ -6,7 +6,6 @@ import codecs
|
|||
import shutil
|
||||
import zipfile
|
||||
import logging
|
||||
import logging.config
|
||||
from string import Template
|
||||
from datetime import datetime
|
||||
from time import strftime
|
||||
|
@ -23,7 +22,6 @@ from dataobjs import PesterProfile, pesterQuirks
|
|||
from parsetools import convertTags
|
||||
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
|
||||
|
@ -274,20 +272,20 @@ with a backup from: <a href='%s'>%s</a></h3></html>" % (_datadir, self.filename,
|
|||
return self.config.get('opvMessages', True)
|
||||
def animations(self):
|
||||
return self.config.get('animations', True)
|
||||
def checkForUpdates(self):
|
||||
u = self.config.get('checkUpdates', 0)
|
||||
if type(u) == type(bool()):
|
||||
if u: u = 2
|
||||
else: u = 3
|
||||
return u
|
||||
# Once a day
|
||||
# Once a week
|
||||
# Only on start
|
||||
# Never
|
||||
def lastUCheck(self):
|
||||
return self.config.get('lastUCheck', 0)
|
||||
def checkMSPA(self):
|
||||
return self.config.get('mspa', False)
|
||||
#def checkForUpdates(self):
|
||||
# u = self.config.get('checkUpdates', 0)
|
||||
# if type(u) == type(bool()):
|
||||
# if u: u = 2
|
||||
# else: u = 3
|
||||
# return u
|
||||
# # Once a day
|
||||
# # Once a week
|
||||
# # Only on start
|
||||
# # Never
|
||||
#def lastUCheck(self):
|
||||
# return self.config.get('lastUCheck', 0)
|
||||
#def checkMSPA(self):
|
||||
# return self.config.get('mspa', False)
|
||||
def blink(self):
|
||||
return self.config.get('blink', self.PBLINK | self.MBLINK)
|
||||
def notify(self):
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
import logging
|
||||
import logging.config
|
||||
import importlib.util
|
||||
|
||||
try:
|
||||
|
@ -11,8 +10,6 @@ except ImportError:
|
|||
import ostools
|
||||
from quirks import ScriptQuirks
|
||||
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
class PythonQuirks(ScriptQuirks):
|
||||
|
|
16
quirks.py
16
quirks.py
|
@ -1,11 +1,9 @@
|
|||
import os
|
||||
import logging
|
||||
import logging.config
|
||||
|
||||
import ostools
|
||||
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
class ScriptQuirks(object):
|
||||
|
@ -37,7 +35,7 @@ class ScriptQuirks(object):
|
|||
if self.last[k] == self.quirks[k]:
|
||||
del self.quirks[k]
|
||||
#print self.quirks
|
||||
if self.quirks:
|
||||
if hasattr(self, 'quirks'):
|
||||
# See https://stackoverflow.com/questions/12843099/python-logging-typeerror-not-all-arguments-converted-during-string-formatting
|
||||
reg_quirks = ('Registered quirks:', '(), '.join(self.quirks) + "()")
|
||||
PchumLog.info(reg_quirks)
|
||||
|
@ -53,13 +51,13 @@ class ScriptQuirks(object):
|
|||
extension = self.getExtension()
|
||||
filenames = []
|
||||
if not os.path.exists(os.path.join(self.home, 'quirks')):
|
||||
os.mkdir(os.path.join(self.home, 'quirks'))
|
||||
os.makedirs(os.path.join(self.home, 'quirks'), exist_ok=True)
|
||||
for fn in os.listdir(os.path.join(self.home, 'quirks')):
|
||||
if fn.endswith(extension) and not fn.startswith('_'):
|
||||
filenames.append(os.path.join(self.home, 'quirks', fn))
|
||||
if self._datadir:
|
||||
if hasattr(self, '_datadir'):
|
||||
if not os.path.exists(os.path.join(self._datadir, 'quirks')):
|
||||
os.mkdir(os.path.join(self._datadir, 'quirks'))
|
||||
os.makedirs(os.path.join(self._datadir, 'quirks'), exist_ok=True)
|
||||
for fn in os.listdir(os.path.join(self._datadir, 'quirks')):
|
||||
if fn.endswith(extension) and not fn.startswith('_'):
|
||||
filenames.append(os.path.join(self._datadir, 'quirks', fn))
|
||||
|
@ -75,10 +73,6 @@ class ScriptQuirks(object):
|
|||
continue
|
||||
except Exception as e:
|
||||
PchumLog.warning("Error loading %s: %s (in quirks.py)" % (os.path.basename(name), e))
|
||||
#msgbox = QtWidgets.QMessageBox()
|
||||
#msgbox.setWindowTitle("Error!")
|
||||
#msgbox.setText("Error loading %s: %s (in quirks.py)" % (os.path.basename(filename), e))
|
||||
#msgbox.exec()
|
||||
else:
|
||||
if self.modHas(module, 'setup'):
|
||||
module.setup()
|
||||
|
@ -91,7 +85,7 @@ class ScriptQuirks(object):
|
|||
del self.quirks[k]
|
||||
|
||||
def funcre(self):
|
||||
if not self.quirks:
|
||||
if not hasattr(self, 'quirks'):
|
||||
return r"\\[0-9]+"
|
||||
f = r"("
|
||||
for q in self.quirks:
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
import logging
|
||||
import logging.config
|
||||
|
||||
try:
|
||||
from PyQt6 import QtCore, QtWidgets
|
||||
|
@ -9,8 +8,6 @@ except ImportError:
|
|||
|
||||
import ostools
|
||||
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
RANDNICK = "randomEncounter"
|
||||
|
|
2
toast.py
2
toast.py
|
@ -2,7 +2,6 @@ import os
|
|||
#import time
|
||||
import inspect
|
||||
import logging
|
||||
import logging.config
|
||||
|
||||
try:
|
||||
from PyQt6 import QtCore, QtGui, QtWidgets
|
||||
|
@ -13,7 +12,6 @@ except ImportError:
|
|||
import ostools
|
||||
|
||||
_datadir = ostools.getDataDir()
|
||||
logging.config.fileConfig(_datadir + "logging.ini")
|
||||
PchumLog = logging.getLogger('pchumLogger')
|
||||
|
||||
#try:
|
||||
|
|
Loading…
Reference in a new issue