示例#1
0
def settings_page():

    context = {'flash': None}

    if request.method == "POST":
        for field, default in CONFIGURABLE_SETTINGS.items():
            value = request.form.get(field, default)
            if isinstance(default, bool):
                value = value == 'on'
            settings[field] = value
        try:
            settings.save()
            system('pkill -SIGHUP -f viewer.py')
            context['flash'] = {
                'class': "success",
                'message': "Settings were successfully saved."
            }
        except IOError as e:
            context['flash'] = {'class': "error", 'message': e}
        except OSError as e:
            context['flash'] = {'class': "error", 'message': e}
    else:
        settings.load()
    for field, default in DEFAULTS['viewer'].items():
        context[field] = settings[field]

    return template('settings.html', **context)
示例#2
0
def settings_page():

    context = {'flash': None}

    if request.method == "POST":
        for field, default in CONFIGURABLE_SETTINGS.items():
            value = request.POST.get(field, default)
            if isinstance(default, bool):
                value = value == 'on'
            settings[field] = value
        try:
            settings.save()
            sh.sudo('systemctl', 'kill', '--signal=SIGUSR2',
                    'screenly-viewer.service')
            context['flash'] = {
                'class': "success",
                'message': "Settings were successfully saved."
            }
        except IOError as e:
            context['flash'] = {'class': "error", 'message': e}
        except sh.ErrorReturnCode_1 as e:
            context['flash'] = {'class': "error", 'message': e}
    else:
        settings.load()
    for field, default in DEFAULTS['viewer'].items():
        context[field] = settings[field]

    return template('settings', **context)
示例#3
0
def initialize():
    # 加载配置文件
    settings.load(os.path.join(HOME_DIR, ARGS.settings))
    
    loglevel = logging._checkLevel(ARGS.loglevel)
    
    # 日志配置
    log_format = '[%(asctime)-15s %(levelname)s:%(name)s:%(module)s] %(message)s'
    logging.basicConfig(level=loglevel, format=log_format)
示例#4
0
def reload_settings():
    """
    Reload settings if the timestamp of the
    settings file is newer than the settings
    file loaded in memory.
    """

    settings_file = path.join(getenv('HOME'), '.screenly', 'screenly.conf')
    settings_file_mtime = path.getmtime(settings_file)
    settings_file_timestamp = datetime.fromtimestamp(settings_file_mtime)

    if not last_settings_refresh or settings_file_timestamp > last_settings_refresh:
        settings.load()

    global last_setting_refresh
    last_setting_refresh = datetime.utcnow()
示例#5
0
def reload_settings():
    """
    Reload settings if the timestamp of the
    settings file is newer than the settings
    file loaded in memory.
    """

    settings_file = path.join(getenv('HOME'), '.screenly', 'screenly.conf')
    settings_file_mtime = path.getmtime(settings_file)
    settings_file_timestamp = datetime.fromtimestamp(settings_file_mtime)

    if not last_settings_refresh or settings_file_timestamp > last_settings_refresh:
        settings.load()

    logging.getLogger().setLevel(logging.DEBUG if settings['debug_logging'] else logging.INFO)

    global last_setting_refresh
    last_setting_refresh = datetime.utcnow()
示例#6
0
文件: ui.py 项目: krig/jamaendo
    def create_window(self):
        log.debug("Creating main window...")
        self.app = hildon.Program()
        self.window = hildon.StackableWindow()
        self.app.add_window(self.window)

        self.window.set_title("jamaendo")

        self.window.connect("destroy", self.destroy)

        self.CONFDIR = os.path.expanduser('~/MyDocs/.jamaendo')
        jamaendo.set_cache_dir(self.CONFDIR)
        settings.set_filename(os.path.join(self.CONFDIR, 'ui_settings'))
        settings.load()

        postoffice.connect('request-album-cover', self, self.on_request_cover)
        postoffice.connect('request-images', self, self.on_request_images)
        log.debug("Created main window.")
示例#7
0
def run():
    from spider import BlogSpider
    
    while True:
        settings.load(os.path.join(HOME_DIR, ARGS.settings))  # reload settings
        optionses = settings['BLOGS']
        
        blog_spiders = []
        
        for options in optionses:
            bs = BlogSpider(**options)
            bs.start()
            blog_spiders.append(bs)
    
        gevent.joinall(blog_spiders)
        
        logger.info('spider over, wait next')
        
        gevent.sleep(3600 * 24)  # 一天爬一次
示例#8
0
def main():
    # Initiates the PyGame module.
    pygame.init()

    # Instantiates a PyGame Clock.
    main_clock = gameclock.GameClock()

    # Load the settings.
    settings.load()
    graphics.load()

    # Display modes, these are by standard double buffering (for performance reasons) and hardware acceleration (works if fullscreen is enabled).
    if graphics.FULLSCREEN:
        display_modes = DOUBLEBUF | HWSURFACE | FULLSCREEN
    else:
        display_modes = DOUBLEBUF | HWSURFACE

    # Setup the window surface to be used.
    window_surface = pygame.display.set_mode(
        (settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT), display_modes)

    # Initialize the camera.
    camera.create_camera(0, 0, settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT)

    # Initialize the joystick module.
    pygame.joystick.init()

    # Initialize the available joysticks.
    for joystick in ([
            pygame.joystick.Joystick(x)
            for x in range(pygame.joystick.get_count())
    ]):
        joystick.init()

    # Set the allowed events so we don't have to check for events that we don't listen to anyway.
    pygame.event.set_allowed(
        [QUIT, KEYDOWN, KEYUP, JOYAXISMOTION, JOYBUTTONDOWN, JOYBUTTONUP])

    # Set the window caption.
    pygame.display.set_caption(settings.WINDOW_CAPTION)

    # Start the splash screen.
    splash.Splash(window_surface, main_clock)
示例#9
0
    def set_asset(self, uri, duration):
        settings.load()

        if self._arch in ('armv6l', 'armv7l'):
            self._player_args = ['omxplayer', uri]
            self._player_kwargs = {
                'o': settings['audio_output'],
                'layer': 1,
                '_bg': True,
                '_ok_code': [0, 124, 143]
            }
        else:
            self._player_args = ['mplayer', uri, '-nosound']
            self._player_kwargs = {'_bg': True, '_ok_code': [0, 124]}

        if duration and duration != 'N/A':
            self._player_args = [
                'timeout', VIDEO_TIMEOUT + int(duration.split('.')[0])
            ] + self._player_args
示例#10
0
def settings_page():

    context = {'flash': None}

    if request.method == "POST":
        for field, default in DEFAULTS['viewer'].items():
            value = request.POST.get(field, default)
            if isinstance(default, bool):
                value = value == 'on'
            settings[field] = value
        try:
            settings.save()
            context['flash'] = {'class': "success", 'message': "Settings were successfully saved."}
        except IOError as e:
            context['flash'] = {'class': "error", 'message': e}
    else:
        settings.load()
    for field, default in DEFAULTS['viewer'].items():
        context[field] = settings[field]

    return template('settings', **context)
示例#11
0
def main():
    # Import config to load configurations
    try:
        config = settings.load('settings.ini')
    except FileNotFoundError as file_error:
        print('Run setup.py first.')
        raise

    # Placeholder for new chapters
    try:
        new_chapters = get_new_chapters(config['MANGA']['latest'],
                                        config['RSS']['url'])
    except KeyError as key_error:
        if key_error.args[0] in ('MANGA', 'latest'):
            new_chapters = get_newest_chapter(config['RSS']['url'])
        else:
            raise

    if new_chapters:
        try:
            push = pushbullet.Push(config['PUSHBULLET']['access_token'])
            push.delete(config['PUSHBULLET']['iden'])
        except KeyError as key_error:
            if key_error.args[0] == 'iden':
                pass
            elif key_error.args[0] == 'PUSHBULLET':
                print('Pusbullet section is missing. Run setup.py.')
                raise
            elif key_error.args[0] == 'access_token':
                print('Pushbullet access token is missing. Run setup.py.')
                raise
            else:
                raise

        config['MANGA']['latest'] = new_chapters[0]['id']
        config['MANGA']['title'] = new_chapters[0]['title']

        body = []
        for index in range(len(new_chapters)):
            body.append(new_chapters[index - 1]['title'] + '\n')

        body.sort()
        body = ''.join(body)

        data = {
            'iden': uuid.uuid4(),
            'type': 'note',
            'title': 'New chapters to read!',
            'body': body
        }
        config['PUSHBULLET']['iden'] = push.create(data)

        settings.save(config, 'settings.ini')
示例#12
0
def settings_page():

    context = {'flash': None}

    if request.method == "POST":
        for field, default in DEFAULTS['viewer'].items():
            value = request.POST.get(field, default)
            if isinstance(default, bool):
                value = value == 'on'
            settings[field] = value
        try:
            settings.save()
            context['flash'] = {'class': "success", 'message': "Settings were successfully saved."}
        except IOError as e:
            context['flash'] = {'class': "error", 'message': e}
    else:
        settings.load()
    for field, default in DEFAULTS['viewer'].items():
        context[field] = settings[field]

    return template('settings', **context)
示例#13
0
def settings_page():

    context = {"flash": None}

    if request.method == "POST":
        for field, default in DEFAULTS["viewer"].items():
            value = request.POST.get(field, default)
            if isinstance(default, bool):
                value = value == "on"
            settings[field] = value
        try:
            settings.save()
            context["flash"] = {"class": "success", "message": "Settings were successfully saved."}
        except IOError as e:
            context["flash"] = {"class": "error", "message": e}
    else:
        settings.load()
    for field, default in DEFAULTS["viewer"].items():
        context[field] = settings[field]

    return template("settings", **context)
示例#14
0
    def __init__(self):
        global home
        home = getenv('HOME', '/home/pi')
        self.currentId = None
        self.currentDirectory = None
        self.worker = None

        signal(SIGUSR1, sigusr1)
        signal(SIGUSR2, sigusr2)

        settings.load()
        logging.getLogger().setLevel(logging.INFO)

        try:
            sh.mkdir(SCREENLY_HTML)
        except:
            pass
        html_templates.black_page(BLACK_PAGE)

        load_browser(url='http://{0}:{1}/splash_page'.format(
            settings.get_listen_ip(), settings.get_listen_port()))
        sleep(30)
示例#15
0
def main():
	# Initiates the PyGame module.
	pygame.init()

	# Instantiates a PyGame Clock.
	main_clock = gameclock.GameClock()

	# Load the settings.
	settings.load()
	graphics.load()

	# Display modes, these are by standard double buffering (for performance reasons) and hardware acceleration (works if fullscreen is enabled).
	if graphics.FULLSCREEN:
		display_modes = DOUBLEBUF | HWSURFACE | FULLSCREEN
	else:
		display_modes = DOUBLEBUF | HWSURFACE

	# Setup the window surface to be used.
	window_surface = pygame.display.set_mode((settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT), display_modes)

	# Initialize the camera.
	camera.create_camera(0, 0, settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT)

	# Initialize the joystick module.
	pygame.joystick.init()

	# Initialize the available joysticks.
	for joystick in ([pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]):
		joystick.init()
	
	# Set the allowed events so we don't have to check for events that we don't listen to anyway.
	pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP, JOYAXISMOTION, JOYBUTTONDOWN, JOYBUTTONUP])

	# Set the window caption.
	pygame.display.set_caption(settings.WINDOW_CAPTION)

	# Start the splash screen.
	splash.Splash(window_surface, main_clock)
示例#16
0
def settings_page():

    context = {'flash': None}

    if request.method == "POST":
        for field, default in CONFIGURABLE_SETTINGS.items():
            value = request.POST.get(field, default)
            if isinstance(default, bool):
                value = value == 'on'
            settings[field] = value
        try:
            settings.save()
            sh.sudo('systemctl', 'kill', '--signal=SIGUSR2', 'screenly-viewer.service')
            context['flash'] = {'class': "success", 'message': "Settings were successfully saved."}
        except IOError as e:
            context['flash'] = {'class': "error", 'message': e}
        except sh.ErrorReturnCode_1 as e:
            context['flash'] = {'class': "error", 'message': e}
    else:
        settings.load()
    for field, default in DEFAULTS['viewer'].items():
        context[field] = settings[field]

    return template('settings', **context)
示例#17
0
def load_settings():
    """Load settings and set the log level."""
    settings.load()
    logging.getLogger().setLevel(logging.DEBUG if settings['debug_logging'] else logging.INFO)
示例#18
0
def settings_page():

    context = {'flash': None}

    if request.method == "POST":
        try:
            # put some request variables in local variables to make easier to read
            current_pass = request.form.get('curpassword', '')
            new_pass = request.form.get('password', '')
            new_pass2 = request.form.get('password2', '')
            current_pass = '' if current_pass == '' else hashlib.sha256(
                current_pass).hexdigest()
            new_pass = '' if new_pass == '' else hashlib.sha256(
                new_pass).hexdigest()
            new_pass2 = '' if new_pass2 == '' else hashlib.sha256(
                new_pass2).hexdigest()

            new_user = request.form.get('user', '')
            use_auth = request.form.get('use_auth', '') == 'on'

            # Handle auth components
            if settings['password'] != '':  # if password currently set,
                if new_user != settings['user']:  # trying to change user
                    # should have current password set. Optionally may change password.
                    if current_pass == '':
                        if not use_auth:
                            raise ValueError(
                                "Must supply current password to disable authentication"
                            )
                        raise ValueError(
                            "Must supply current password to change username")
                    if current_pass != settings['password']:
                        raise ValueError("Incorrect current password.")

                    settings['user'] = new_user

                if new_pass != '' and use_auth:
                    if current_pass == '':
                        raise ValueError(
                            "Must supply current password to change password")
                    if current_pass != settings['password']:
                        raise ValueError("Incorrect current password.")

                    if new_pass2 != new_pass:  # changing password
                        raise ValueError("New passwords do not match!")

                    settings['password'] = new_pass

                if new_pass == '' and not use_auth and new_pass2 == '':
                    # trying to disable authentication
                    if current_pass == '':
                        raise ValueError(
                            "Must supply current password to disable authentication"
                        )
                    settings['password'] = ''

            else:  # no current password
                if new_user != '':  # setting username and password
                    if new_pass != '' and new_pass != new_pass2:
                        raise ValueError("New passwords do not match!")
                    if new_pass == '':
                        raise ValueError("Must provide password")
                    settings['user'] = new_user
                    settings['password'] = new_pass

            for field, default in CONFIGURABLE_SETTINGS.items():
                value = request.form.get(field, default)

                # skip user and password as they should be handled already.
                if field == "user" or field == "password":
                    continue

                if isinstance(default, bool):
                    value = value == 'on'
                settings[field] = value

            settings.save()
            publisher = ZmqPublisher.get_instance()
            publisher.send_to_viewer('reload')
            context['flash'] = {
                'class': "success",
                'message': "Settings were successfully saved."
            }
        except ValueError as e:
            context['flash'] = {'class': "danger", 'message': e}
        except IOError as e:
            context['flash'] = {'class': "danger", 'message': e}
        except OSError as e:
            context['flash'] = {'class': "danger", 'message': e}
    else:
        settings.load()
    for field, default in DEFAULTS['viewer'].items():
        context[field] = settings[field]

    context['user'] = settings['user']
    context['password'] = "******" if settings['password'] != "" else ""

    context['reset_button_state'] = "disabled" if path.isfile(
        path.join(HOME, DISABLE_MANAGE_NETWORK)) else ""

    if not settings['user'] or not settings['password']:
        context['use_auth'] = False
    else:
        context['use_auth'] = True

    return template('settings.html', **context)
示例#19
0
from tangiblePattern	import tangibles


# clear screen and print program info
os.system('cls' if os.name=='nt' else 'clear')

print "Vega - TUIO proxy Copyright (C) 2012 Thomas Becker"
print "This program comes with ABSOLUTELY NO WARRANTY."
print "This is free software, and you are welcome to redistribute it"
print "under certain conditions."
print ""

print "TUIO proxy started"

# load settings from files
settings.load()

# load tangibles from disk
tangibles.loadTangiblesFromDisk()

# start the tuio proxy
tuioServer.start()

# start remote control for this programm
remote.start()

print "TUIO proxy up and running..."

try :
	while 1 :
		pass
示例#20
0
def load_settings():
    """Load settings and set the log level."""
    settings.load()
    logging.getLogger().setLevel(logging.DEBUG if settings['debug_logging'] else logging.INFO)
示例#21
0
def settings_page():
    context = {'flash': None}

    if request.method == "POST":
        try:
            # put some request variables in local variables to make easier to read
            current_pass = request.form.get('current-password', '')
            auth_backend = request.form.get('auth_backend', '')

            if auth_backend != settings['auth_backend'] and settings[
                    'auth_backend']:
                if not current_pass:
                    raise ValueError(
                        "Must supply current password to change authentication method"
                    )
                if not settings.auth.check_password(current_pass):
                    raise ValueError("Incorrect current password.")

            prev_auth_backend = settings['auth_backend']
            if not current_pass and prev_auth_backend:
                current_pass_correct = None
            else:
                current_pass_correct = settings.auth_backends[
                    prev_auth_backend].check_password(current_pass)
            next_auth_backend = settings.auth_backends[auth_backend]
            next_auth_backend.update_settings(current_pass_correct)
            settings['auth_backend'] = auth_backend

            for field, default in CONFIGURABLE_SETTINGS.items():
                value = request.form.get(field, default)

                if not value and field in [
                        'default_duration', 'default_streaming_duration'
                ]:
                    value = str(0)

                if isinstance(default, bool):
                    value = value == 'on'
                settings[field] = value

            settings.save()
            publisher = ZmqPublisher.get_instance()
            publisher.send_to_viewer('reload')
            context['flash'] = {
                'class': "success",
                'message': "Settings were successfully saved."
            }
        except ValueError as e:
            context['flash'] = {'class': "danger", 'message': e}
        except IOError as e:
            context['flash'] = {'class': "danger", 'message': e}
        except OSError as e:
            context['flash'] = {'class': "danger", 'message': e}
    else:
        settings.load()
    for field, default in DEFAULTS['viewer'].items():
        context[field] = settings[field]

    auth_backends = []
    for backend in settings.auth_backends_list:
        if backend.template:
            html, ctx = backend.template
            context.update(ctx)
        else:
            html = None
        auth_backends.append({
            'name':
            backend.name,
            'text':
            backend.display_name,
            'template':
            html,
            'selected':
            'selected' if settings['auth_backend'] == backend.name else ''
        })

    context.update({
        'user': settings['user'],
        'need_current_password': bool(settings['auth_backend']),
        'is_balena': is_balena_app(),
        'auth_backend': settings['auth_backend'],
        'auth_backends': auth_backends
    })

    return template('settings.html', **context)
示例#22
0
def settings_page():
    context = {'flash': None}

    if request.method == "POST":
        try:
            # put some request variables in local variables to make easier to read
            current_pass = request.form.get('curpassword', '')
            new_pass = request.form.get('password', '')
            new_pass2 = request.form.get('password2', '')
            current_pass = '' if current_pass == '' else hashlib.sha256(current_pass).hexdigest()
            new_pass = '' if new_pass == '' else hashlib.sha256(new_pass).hexdigest()
            new_pass2 = '' if new_pass2 == '' else hashlib.sha256(new_pass2).hexdigest()

            new_user = request.form.get('user', '')
            use_auth = request.form.get('use_auth', '') == 'on'

            # Handle auth components
            if settings['password'] != '':  # if password currently set,
                if new_user != settings['user']:  # trying to change user
                    # should have current password set. Optionally may change password.
                    if current_pass == '':
                        if not use_auth:
                            raise ValueError("Must supply current password to disable authentication")
                        raise ValueError("Must supply current password to change username")
                    if current_pass != settings['password']:
                        raise ValueError("Incorrect current password.")

                    settings['user'] = new_user

                if new_pass != '' and use_auth:
                    if current_pass == '':
                        raise ValueError("Must supply current password to change password")
                    if current_pass != settings['password']:
                        raise ValueError("Incorrect current password.")

                    if new_pass2 != new_pass:  # changing password
                        raise ValueError("New passwords do not match!")

                    settings['password'] = new_pass

                if new_pass == '' and not use_auth and new_pass2 == '':
                    # trying to disable authentication
                    if current_pass == '':
                        raise ValueError("Must supply current password to disable authentication")
                    settings['password'] = ''

            else:  # no current password
                if new_user != '':  # setting username and password
                    if new_pass != '' and new_pass != new_pass2:
                        raise ValueError("New passwords do not match!")
                    if new_pass == '':
                        raise ValueError("Must provide password")
                    settings['user'] = new_user
                    settings['password'] = new_pass

            for field, default in CONFIGURABLE_SETTINGS.items():
                value = request.form.get(field, default)

                # skip user and password as they should be handled already.
                if field == "user" or field == "password":
                    continue

                if not value and field in ['default_duration', 'default_streaming_duration']:
                    value = str(0)

                if isinstance(default, bool):
                    value = value == 'on'
                settings[field] = value

            settings.save()
            publisher = ZmqPublisher.get_instance()
            publisher.send_to_viewer('reload')
            context['flash'] = {'class': "success", 'message': "Settings were successfully saved."}
        except ValueError as e:
            context['flash'] = {'class': "danger", 'message': e}
        except IOError as e:
            context['flash'] = {'class': "danger", 'message': e}
        except OSError as e:
            context['flash'] = {'class': "danger", 'message': e}
    else:
        settings.load()
    for field, default in DEFAULTS['viewer'].items():
        context[field] = settings[field]

    context['user'] = settings['user']
    context['password'] = "******" if settings['password'] != "" else ""

    context['is_balena_app'] = is_balena_app()

    if not settings['user'] or not settings['password']:
        context['use_auth'] = False
    else:
        context['use_auth'] = True

    return template('settings.html', **context)
示例#23
0
import re
import sys
from datetime import datetime
from getpass import getpass
from time import sleep

from log import Log
from oc import oc_client
from ping import ping
from settings import settings

settings.load()
oc_client.kill_existing_oc()
ping_address = settings.g.get('ping_address', '8.8.8.8')

current_pid = None
get_from_env = True

settings.is_background = '-b' in sys.argv
if '-s' in sys.argv:
    si = sys.argv.index('-s')
    if si:
        settings.file_path = sys.argv[si + 1]

if '-k' in sys.argv:
    ki = sys.argv.index('-k')
    if ki:
        oc_client.key = sys.argv[ki + 1]

profile_index = 0
if '-i' in sys.argv:
示例#24
0
def load_settings():
    """Load settings and set the log level."""
    settings.load()
示例#25
0
文件: app.py 项目: waldvogel/taxi
def main():
    """Usage: %prog [options] command

Available commands:
  add    \t\tsearches, prompts for project, activity and alias, adds to .tksrc
  commit \t\tcommits the changes to the server
  edit   \t\topens your zebra file in your favourite editor
  help   \t\tprints this help or the one of the given command
  search \t\tsearches for a project
  show   \t\tshows the activities and other details of a project
  start  \t\tstarts the counter on a given activity
  status \t\tshows the status of your entries file
  stop   \t\tstops the counter and record the elapsed time
  update \t\tupdates your project database with the one on the server
  autofill \t\tautofills the current timesheet with all the days of the month"""

    usage = main.__doc__
    locale.setlocale(locale.LC_ALL, '')

    opt = OptionParser(usage=usage, version='%prog ' + taxi.__version__)
    opt.add_option('-c', '--config', dest='config', help='use CONFIG file instead of ~/.tksrc', default=os.path.join(os.path.expanduser('~'), '.tksrc'))
    opt.add_option('-v', '--verbose', dest='verbose', action='store_true', help='make taxi verbose', default=False)
    opt.add_option('-f', '--file', dest='file', help='parse FILE instead of the '\
            'one defined in your CONFIG file')
    opt.add_option('-d', '--date', dest='date', help='only process entries for date '\
            'DATE (eg. 31.01.2011, 31.01.2011-05.02.2011)')
    opt.add_option('--ignore-date-error',
            dest='ignore_date_error', help='suppresses the error if'\
            ' you\'re trying to commit a date that\'s on a week-end or on another'\
            ' day than the current day or the day before', action='store_true', default=False)
    (options, args) = opt.parse_args()

    args = [term_unicode(arg) for arg in args]

    actions = [
            (['stat', 'status'], status),
            (['ci', 'commit'], commit),
            (['up', 'update'], update),
            (['search'], search),
            (['show'], show),
            (['start'], start),
            (['stop'], stop),
            (['edit'], edit),
            (['add'], add),
            (['autofill'], autofill),
    ]

    if len(args) == 0 or (len(args) == 1 and args[0] == 'help'):
        opt.print_help()
        exit()

    settings.load(options.config)
    if not os.path.exists(settings.TAXI_PATH):
        os.mkdir(settings.TAXI_PATH)

    if options.file is None:
        try:
            options.file = settings.get('default', 'file')
        except ConfigParser.NoOptionError:
            raise Exception("""Error: no file to parse. You must either define \
one in your config file with the 'file' setting, or use the -f option""")

    options.unparsed_file = options.file
    options.file = datetime.date.today().strftime(os.path.expanduser(options.file))

    if options.date is not None:
        date_format = '%d.%m.%Y'

        try:
            if '-' in options.date:
                splitted_date = options.date.split('-', 1)

                options.date = (datetime.datetime.strptime(splitted_date[0],\
                        date_format).date(),
                        datetime.datetime.strptime(splitted_date[1],
                            date_format).date())
            else:
                options.date = datetime.datetime.strptime(options.date,\
                        date_format).date()
        except ValueError:
            opt.print_help()
            exit()

    try:
        call_action(actions, options, args)
    except ProjectNotFoundError as e:
        if options.verbose:
            raise

        print e.description
        print suggest_project_names(e.project_name)
    except Exception as e:
        if options.verbose:
            raise

        print e
示例#26
0
def main():

    try:
        config = settings.load('settings.ini')
    except FileNotFoundError as file_error:
        print('Run setup.py first.')
        raise

    try:
        latitude = config['COORDINATES']['latitude']
        longitude = config['COORDINATES']['longitude']
    except KeyError as key_error:
        if key_error.args[0] in ('COORDINATES', 'latitude', 'longitude'):
            print('Run setup.py.')
        raise

    category = 'pmp3g'
    version = 2

    url = f"https://opendata-download-metfcst.smhi.se/api/category/{category}/version/{version}/geotype/point/lon/{longitude}/lat/{latitude}/data.json"
    resp = requests.get(url).json()

    body = []
    # day = weekday_name( datetime.strptime(resp['timeSeries'][1]['validTime'], '%Y-%m-%dT%H:%M:%SZ').weekday())
    day = ''

    for index in range(12):
        date = resp['timeSeries'][index]['validTime']
        parameters = resp['timeSeries'][index]['parameters']
        air_temperature = next(
            (param for param in parameters if param['name'] == 't'), 'No data')
        wind_speed = next(
            (param for param in parameters if param['name'] == 'ws'),
            'No data')
        weather = _Weather(
            next((param for param in parameters if param['name'] == 'Wsymb2'),
                 'No data')['values'][0])

        if air_temperature['unit'] == 'Cel':
            degree_unit = u'\N{DEGREE SIGN}'
        else:
            degree_unit = air_temperature['unit']

        date = datetime.strptime(date, '%Y-%m-%dT%H:%M:%SZ')
        clock = _Clock(date.hour, date.minute)

        if day != weekday_name(date.weekday()):
            body.append(f"{weekday_name(date.weekday())}:")
        day = weekday_name(date.weekday())

        body.append(
            f"{clock.time} - {air_temperature['values'][0]}{degree_unit} - {wind_speed['values'][0]}{wind_speed['unit']} - {weather.forecast}"
        )

    body = '\n'.join(body)

    try:
        push = pushbullet.Push(config['PUSHBULLET']['access_token'])
        push.delete(config['PUSHBULLET']['iden'])
    except KeyError as key_error:
        if key_error.args[0] == 'iden':
            pass
        elif key_error.args[0] == 'PUSHBULLET':
            print('Pusbullet section is missing. Run setup.py.')
            raise
        elif key_error.args[0] == 'access_token':
            print('Pushbullet access token is missing. Run setup.py.')
            raise
        else:
            raise

    data = {
        'iden': uuid.uuid4(),
        'type': 'note',
        'title': 'Todays forecast',
        'body': body
    }
    config['PUSHBULLET']['iden'] = push.create(data)
    settings.save(config, 'settings.ini')