aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorFilipp Lepalaan <filipp@mac.com>2017-03-24 22:36:27 +0200
committerFilipp Lepalaan <filipp@mac.com>2017-03-24 22:36:27 +0200
commit469ff60b8bf3ee0273f8a8fc80c2ddbe4cacd47d (patch)
tree3f7376766fef8aa551582a1352ae61c9c3356e67
parent66ac3ea8dbf8c88b7d666183edaa34df0688795d (diff)
downloadmachammer-469ff60b8bf3ee0273f8a8fc80c2ddbe4cacd47d.tar.gz
machammer-469ff60b8bf3ee0273f8a8fc80c2ddbe4cacd47d.tar.bz2
machammer-469ff60b8bf3ee0273f8a8fc80c2ddbe4cacd47d.zip
Added more stuff
-rw-r--r--machammer/functions.py30
-rw-r--r--machammer/network.py14
-rw-r--r--machammer/printers.py53
-rwxr-xr-xmachammer/process.py26
-rw-r--r--machammer/screensaver.py9
-rwxr-xr-xtests.py26
6 files changed, 117 insertions, 41 deletions
diff --git a/machammer/functions.py b/machammer/functions.py
index 522c517..6600118 100644
--- a/machammer/functions.py
+++ b/machammer/functions.py
@@ -6,9 +6,9 @@ import logging
import plistlib
import tempfile
import subprocess
-
from xml.parsers.expat import ExpatError
-from system_profiler import SystemProfile
+
+from .system_profiler import SystemProfile
SERVICEDIR = '/Library/Services'
@@ -25,13 +25,27 @@ def get_plist(path):
def call(*args):
- """Shorthand for subprocess.call.
+ """Shortcut for subprocess.call.
> call('ls', '/Users')
"""
subprocess.call(args)
+def popen(cmd, input=None):
+ """Shortcut for Popen/communicate()."""
+ proc = subprocess.Popen(cmd,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+ (res, err) = proc.communicate(input)
+
+ if err:
+ raise Exception(err)
+
+ return res
+
+
def check_output(*args):
"""Shortcut for subprocess.check_output."""
result = subprocess.check_output(args).strip()
@@ -44,7 +58,7 @@ def check_output(*args):
def rmdir(path):
"""Shortcut for deleting a directory."""
- call('rm', '-r', path)
+ call('/bin/rm', '-r', path)
def display_notification(msg, title='', subtitle=''):
@@ -201,12 +215,6 @@ def install_su(restart=True):
sys.exit(0)
-def disable_wifi(port='en1'):
- ns = '/usr/sbin/networksetup'
- call(ns, '-setairportpower', port, 'off')
- call(ns, '-setnetworkserviceenabled', 'Wi-Fi', 'off')
-
-
def install_service(src):
"""Copy .service to systemwide Services folder."""
if not os.path.exists(SERVICEDIR):
@@ -233,4 +241,4 @@ def curl(url, *args):
def log(msg):
- print('*** %s...' % msg)
+ logging.debug(msg)
diff --git a/machammer/network.py b/machammer/network.py
index 2c4dcfc..e1a9058 100644
--- a/machammer/network.py
+++ b/machammer/network.py
@@ -1,9 +1,12 @@
# -*- coding: utf-8 -*-
"""Network-related machammer functions."""
+from .process import kill
from .functions import call, check_output
from .system_profiler import SystemProfile
+NETWORKSETUP = '/usr/sbin/networksetup'
+
def get_ports(type='Ethernet'):
"""Return all devices of type (Ethernet, AirPort)"""
@@ -15,7 +18,12 @@ def set_wifi_power(on=True):
"""Set AirPort power to on (True) or off (False)"""
state = 'on' if on else 'off'
for i in get_ports('AirPort'):
- call('/usr/sbin/networksetup', '-setairportpower', i['interface'], state)
+ call(NETWORKSETUP, '-setairportpower', i['interface'], state)
+
+
+def disable_wifi(port='en1'):
+ call(NETWORKSETUP, '-setairportpower', port, 'off')
+ call(NETWORKSETUP, '-setnetworkserviceenabled', 'Wi-Fi', 'off')
def get_wifi_power():
@@ -23,7 +31,7 @@ def get_wifi_power():
results = []
for i in get_ports('AirPort'):
iface = i['interface']
- r = check_output('/usr/sbin/networksetup', '-getairportpower', iface)
+ r = check_output(NETWORKSETUP, '-getairportpower', iface)
results.append(r.split(': ')[1])
return 'On' in results
@@ -59,4 +67,4 @@ def get_primary(port=None):
def flush_dns():
"""Flush the DNS cache."""
- call('/usr/bin/killall', '-HUP', 'mDNSResponder')
+ kill('mDNSResponder', 'HUP')
diff --git a/machammer/printers.py b/machammer/printers.py
index d3c7539..55fd31d 100644
--- a/machammer/printers.py
+++ b/machammer/printers.py
@@ -1,39 +1,52 @@
# -*- coding: utf-8 -*-
-import subprocess
+from .functions import call, popen, check_output, log
+
+LPSTAT = '/usr/bin/lpstat'
+LPADMIN = '/usr/sbin/lpadmin'
+
+
+def reset():
+ """Reset this printing system."""
+ pass
+
+
+def delete_printer(printer):
+ log('Deleting printer %s' % printer)
+ return call(LPADMIN, '-x', printer)
def delete_printers():
- for p in subprocess.check_output(['lpstat', '-p']).strip().split("\n"):
- subprocess.call(['lpadmin', '-x', p[1]])
+ """Delete all print queues on the system."""
+ for p in check_output(LPSTAT, '-p').split("\n"):
+ printer = p.split(' ')[1]
+ delete_printer(printer)
-def add_printer(printer, options={}):
- """
- Add a printer
+def add_printer(printer, options={}, delete=True):
+ """Add a printer queue.
+
A printer is a tuple (name, PPD path, LPD address)
"""
- cmd = ['/usr/sbin/lpadmin', '-x', printer[1]]
- proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- (lpadminxOut, lpadminxErr) = proc.communicate()
+ if delete:
+ delete_printer(printer[1])
+
+ name = printer[0]
+ ppd = '/Library/Printers/PPDs/Contents/Resources/%s' % printer[1]
# Install the printer
cmd = ['/usr/sbin/lpadmin',
- '-p', printer[0].replace(' ', '-'),
- '-L', printer[0][0:2],
- '-D', printer[0],
+ '-p', name.replace(' ', '-'),
+ '-L', name[0:2],
+ '-D', name,
'-v', 'lpd://%s' % printer[2],
- '-P', '/Library/Printers/PPDs/Contents/Resources/%s' % printer[1],
+ '-P', ppd,
'-E',
'-o', 'printer-is-shared=false',
'-o', 'printer-error-policy=abort-job']
for option in options.keys():
- cmd.append("-o")
- cmd.append(str(option) + "=" + str(options[option]))
-
- proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- (res, err) = proc.communicate()
+ cmd.append('-o')
+ cmd.append(str(option) + '=' + str(options[option]))
- if err:
- raise Exception(err)
+ return popen(cmd)
diff --git a/machammer/process.py b/machammer/process.py
index d445e07..59160c6 100755
--- a/machammer/process.py
+++ b/machammer/process.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
-from .functions import osascript, call
+from .functions import call, tell_app
def pidof(name):
@@ -8,12 +8,30 @@ def pidof(name):
def is_running(name):
- pass
+ s = 'name of every application process contains "%s"' % name
+ a = tell_app('System Events', s)
+ return a == 'true'
+
+
+def is_active(name):
+ """Return True if process with name is frontmost
+ """
+ s = 'name of first application process whose frontmost is true'
+ a = tell_app('System Events', s)
+ return a == name
+
+
+def activate(name):
+ tell_app(name, 'activate')
def quit(name):
pass
-def kill(name):
- pass
+def kill(name, signal='TERM'):
+ call('/usr/bin/killall', '-' + signal, name)
+
+
+def open(name):
+ call('/usr/bin/open', '-a', name)
diff --git a/machammer/screensaver.py b/machammer/screensaver.py
index 0910214..8e51046 100644
--- a/machammer/screensaver.py
+++ b/machammer/screensaver.py
@@ -1,13 +1,13 @@
from .functions import tell_app
-
def get():
return tell_app('System Events', 'get name of current screen saver')
def set(name):
- return tell_app('System Events', 'set current screen saver to (get screen saver named "%s")' % name)
+ s = 'set current screen saver to (get screen saver named "%s")' % name
+ return tell_app('System Events', s)
def start():
@@ -16,3 +16,8 @@ def start():
def stop():
return tell_app('System Events', 'stop current screen saver')
+
+
+def is_running():
+ running = tell_app('System Events', 'running of screen saver preferences')
+ return running == 'true'
diff --git a/tests.py b/tests.py
index 85eee77..ef606ae 100755
--- a/tests.py
+++ b/tests.py
@@ -9,7 +9,31 @@ from unittest import main, skip, TestCase
from machammer import (functions, system_profiler,
network, hooks, users,
- screensaver, defaults,)
+ screensaver, defaults,
+ printers, process,)
+
+
+class PrintersTestCase(TestCase):
+ def test_delete_printers(self):
+ printers.delete_printers()
+
+
+class ProcessTestCase(TestCase):
+ def setUp(self):
+ self.appname = 'Stickies'
+
+ def test_kill(self):
+ process.kill(self.appname)
+ self.assertFalse(process.is_running(self.appname))
+
+ def test_open(self):
+ process.open(self.appname)
+ self.assertTrue(process.is_running(self.appname))
+
+ def test_activate(self):
+ process.activate(self.appname)
+ time.sleep(2)
+ self.assertTrue(process.is_active(self.appname))
class SystemProfilerTestCase(TestCase):