This repository has been archived by the owner on Sep 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autorun.py
216 lines (163 loc) · 5.65 KB
/
autorun.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#!/usr/bin/env python
#
# Autorun
#
# Autorun is a script designed to run programs based on conditions that you might not found
# in many task schedulers.
#
# Why? I wanted to autorun my work applications on system startup, but couldn't configure
# any software to skip holidays and weekends, or days where people usually don't have work.
#
# Copyright (c) 2012 Beau Hastings. All rights reserved.
# License: GNU GPL version 2, see LICENSE for more details.
#
# Author: Beau Hastings <beausy@gmail.com>
APP_AUTHOR = "Beau Hastings"
APP_EMAIL = "beausy@gmail.com"
APP_GIT = "http://github.com/hastinbe/py-autorun.git"
APP_NAME = "Autorun"
APP_VERSION = "0.1.0-alpha"
# Standard Python imports.
import contextlib
import datetime
import subprocess
import time
import urllib2
import logging
# Log a message each time this module gets loaded.
logging.info('Loading %s, app version = %s', __name__, APP_VERSION)
# Application imports.
import settings
# 3rd party imports.
import psutil
from icalendar import Calendar
# --------------------------------------------------------------------------------------------------
class Autorun(object):
"""
Provides an interface for executing applications under specified conditions.
Public methods:
start
Protected methods:
_has_internet
_is_running
_is_holiday
_is_weekend
Attributes:
apps (dict) Applications to autorun.
ical (str) Path to an iCalendar file.
"""
# Cached result of has_internet()
_has_internet_result = False
# Time in seconds the cached result expires
_has_internet_expires = 60
# Time in seconds since epoch that has_internet() was last called
_has_internet_timeout = None
def __init__ (self, apps, ical):
"""
Create a new `Autorun` instance.
Args:
apps (dict) Applications to autorun.
ical (str) Path to an iCalendar file.
"""
self.apps = apps
self.ical = ical
# ------------------------------------------------------------------------------------------------
def start (self):
"""
Executes autostart applications in the background.
"""
for app, params in self.apps.iteritems():
if params['conditions'].get('skip_if_running'):
if self._is_running(app):
continue
if params['conditions'].get('skip_if_holiday'):
if self._is_holiday():
continue
if params['conditions'].get('skip_if_weekend'):
if self._is_weekend():
continue
if params['conditions'].get('require_internet'):
if not self._has_internet(settings.urls, settings.url_timeout):
continue
args = [params['path']]
if not params['args'] is None:
args.append(params['args'])
subprocess.Popen(args)
# ------------------------------------------------------------------------------------------------
def _has_internet (self, urls, timeout=30):
"""
Determine if there is an internet connection.
The result is cached to prevent checking each URL for each application
that has the require_internet condition set to `True`.
Args:
urls (list) A list of URLs used to determine internet connectivity.
timeout (int) Optional time in seconds to block during the connection attempt. (default 30)
Returns:
(bool) `True`, if an internet connection is available, otherwise `False`.
"""
if self._has_internet_timeout is None:
self._has_internet_timeout = time.time()
t = time.time()
if t - self._has_internet_timeout > self._has_internet_expires:
return self._has_internet_result
try:
for url in urls:
with contextlib.closing(urllib2.urlopen(url, timeout=timeout)):
self._has_internet_result = True
self._has_internet_timeout = t
return True
except urllib2.URLError:
pass
self._has_internet_result = False
self._has_internet_timeout = None
return False
# ------------------------------------------------------------------------------------------------
def _is_running (self, app_name):
"""
Check if `app_name` is running.
Args:
app_name (str) The name of the application.
Returns:
(bool) `True`, if application is running, otherwise `False`.
"""
try:
for proc in psutil.get_process_list():
if proc.name == app_name:
return True
except:
pass
return False
# ------------------------------------------------------------------------------------------------
def _is_holiday (self, date=None):
"""
Check if `date` is a US holiday.
Args:
date (datetime.date) Optional date. (default today's date)
Returns:
(bool) `True`, if date is a holiday, otherwise `False`.
"""
if date is None:
date = datetime.date.today()
calendar = Calendar.from_ical(open(self.ical, 'rb').read())
holidays = [e['dtstart'] for e in calendar.walk('VEVENT')]
date_str = date.strftime('%Y%m%d')
for holiday in holidays:
if holiday.to_ical() == date_str:
return True
return False
# ------------------------------------------------------------------------------------------------
def _is_weekend (self, date=None):
"""
Check if `date` is a weekend
Args:
date (datetime.date) Optional date. (default today's date)
Returns:
(bool) `True`, if date falls on a weekend, otherwise `False`.
"""
if date is None:
date = datetime.date.today()
return date.isoweekday() > 5
# --------------------------------------------------------------------------------------------------
if __name__ == '__main__':
autorun = Autorun(settings.apps, settings.icalendar)
autorun.start()