updated examples to python 3

This commit is contained in:
Fredrick W. Warren 2024-09-09 01:26:31 -06:00
parent 259f902f75
commit 970bb33b46
6 changed files with 67 additions and 69 deletions

View File

@ -28,7 +28,7 @@ First workingish version
"""
usage = """pywmdatetime.py [options]
Available options are:
-h, --help print this help
-h, --help asprint this help
-f, --foreground <color> set the foreground color
-b, --background <color> set the background color
-F, --font <file> set the font name
@ -69,7 +69,7 @@ def addString(s, x, y):
try:
wmdocklib.addString(s, x, y, xOffset, yOffset,
width, height)
except ValueError, e:
except ValueError as e:
sys.stderr.write('Error when painting string:\n' + str(e) + '\n')
sys.stderr.write('test %s' % ((s, x, y, xOffset, yOffset,
width, height),))
@ -119,7 +119,7 @@ def parseCommandLine(argv):
'weekdayformat=', 'weekformat=', 'rgbfile=', 'configfile=', 'font=']
try:
opts, nonOptArgs = getopt.getopt(argv[1:], shorts, longs)
except getopt.GetoptError, e:
except getopt.GetoptError as e:
sys.stderr.write('Error when parsing commandline: ' + str(e) + '\n')
sys.stderr.write(usage)
sys.exit(2)
@ -247,7 +247,7 @@ def main():
# Merge the two configs, let the commandline options overwrite those in the
# configuration file.
config = fileConfig
for i in clConfig.iteritems():
for i in clConfig.items():
config[i[0]] = i[1]
timeFmt = config.get('timeformat', timeDefaultFormat)
@ -282,7 +282,7 @@ def main():
bg=0, fg=2, palette=palette,
background=background,
debug=debug)
maxCharsPerLine = (width-2*xOffset) / char_width
maxCharsPerLine = (width-2*xOffset) // char_width
antialiased = clConfig.get('antialiased', False)
wmdocklib.openXwindow(sys.argv, width, height)

View File

@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""pywmgeneric.py
@ -37,11 +37,13 @@ import sys
import os
import time
import string
import ConfigParser
import configparser
import getopt
import popen2
import subprocess
import wmdocklib
import wmdocklib.pywmgeneral as pywmgeneral
import wmdocklib.pywmhelpers as pywmhelpers
prevStat = {'user':0,
'nice':0,
@ -76,16 +78,14 @@ class UserMethods:
def result():
global prevStat
try:
f = file('/proc/stat', 'r')
with open('/proc/stat', 'r') as f:
currStat = dict(
[(k, int(v))
for (k,v) in cpuinfo.match(f.readline()).groupdict().items()]
)
except IOError:
return 'error'
currStat = dict(
[(k, int(v))
for (k,v) in cpuinfo.match(f.readline()).groupdict().items()]
)
f.close()
total = 0
for k,v in currStat.items():
total += v
@ -105,11 +105,10 @@ class UserMethods:
def getSysTemp(self):
try:
f = file('/proc/sys/dev/sensors/w83697hf-isa-0290/temp1', 'r')
with open('/proc/sys/dev/sensors/w83697hf-isa-0290/temp1', 'r') as f:
temp = f.readline().split()[2]
except IOError:
return lambda: 'error'
temp = f.readline().split()[2]
f.close()
return lambda: 'sys: %s' % temp
def ls(self):
@ -153,8 +152,8 @@ def addString(s, x, y):
try:
wmdocklib.addString(s, x, y, xOffset, yOffset,
width, height)
except ValueError, e:
sys.stderr.write('Error when painting string:\n' + str(e) + '\n')
except ValueError as e:
sys.stderr.write(f'Error when painting string:\n{e}\n')
sys.exit(3)
def clearLine(y):
@ -194,7 +193,7 @@ class Entry:
self._glue = ' ... '
self._scrollPos = 0
self._tickCount = 0L
self._tickCount = 0
self._runningProcs = []
self._actionProc = None
@ -220,7 +219,7 @@ class Entry:
"""Exec an external command in the background.
Return the running process as created by Popen3()."""
proc = popen2.Popen3(command)
proc = subprocess.Popen(command)
self._runningProcs.append(proc)
return proc
@ -480,7 +479,7 @@ class PywmGeneric:
timeNum = float(timeStr[:-1].strip())
numSecs = timeNum * multiplier
return numSecs
raise ValueError, 'Invalid literal'
raise ValueError('Invalid literal')
def _checkForEvents(self):
event = wmdocklib.getEvent()
@ -517,7 +516,7 @@ def parseCommandLine(argv):
'font=', 'debug']
try:
opts, nonOptArgs = getopt.getopt(argv[1:], shorts, longs)
except getopt.GetoptError, e:
except getopt.GetoptError as e:
err('Error when parsing commandline: ' + str(e) + '\n')
err(usage)
sys.exit(2)
@ -551,10 +550,10 @@ def readConfigFile(fileName):
err("Can't read the configuration file %s.\n" % fileName)
# We can't do much without a configuration file
sys.exit(3)
cp = ConfigParser.ConfigParser()
cp = configparser.ConfigParser()
try:
cp.read(fileName)
except ConfigParser.Error, e:
except configparser.Error as e:
err("Error when reading configuration file:\n%s\n" % str(e))
sys.exit(3)
l = [{}, {}, {}, {}, {}]

View File

@ -89,7 +89,7 @@ class PywmHDMon:
self._pathsToMonitor = pathsToMonitor
self._actMonEnabled = actMonEnabled
self._skipping = skipping
self._lineCount = (height - yOffset*2 - 2) / (char_height+1)
self._lineCount = (height - yOffset*2 - 2) // (char_height+1)
self._statFile = procStat
self._maxIODiff = 0
@ -102,7 +102,7 @@ class PywmHDMon:
def addString(self, s, x, y):
try:
wmdocklib.addString(s, x, y, xOffset, yOffset, width, height)
except ValueError, e:
except ValueError as e:
sys.stderr.write('Error when painting string:\n' + str(e) + '\n')
sys.exit(3)
@ -116,7 +116,7 @@ class PywmHDMon:
"""
# check if is mounted <- st_dev(/mount/point) == st_dev(/mount)
if path is not '/':
if path != '/':
statOwn = os.stat(path)
# the following is a bit ugly: it removes the trailing
@ -151,7 +151,7 @@ class PywmHDMon:
def getY(self, line):
"returns the y coordinate of the top line for the box"
interlinea = (height - yOffset*2 - 2 - self._lineCount * char_height) / (self._lineCount-1)
interlinea = (height - yOffset*2 - 2 - self._lineCount * char_height) // (self._lineCount-1)
interlinea += char_height
lastBaseline = yOffset + self._lineCount * interlinea
from math import ceil
@ -163,7 +163,7 @@ class PywmHDMon:
def paintHdData(self, line, data, mode):
total, free = data
xStart = (width*2)/5
xStart = (width*2)//5
if total==0:
self.addString(' ', width-yOffset*2-5*char_width-1, self.getY(line))
self.paintGraph(0, xStart, self.getY(line) + 4,
@ -244,7 +244,7 @@ class PywmHDMon:
sys.exit(0)
elif event['type'] == 'buttonrelease':
area = wmdocklib.checkMouseRegion(event['x'],event['y'])
if area is not -1:
if area != -1:
self.toggleMount(area-1+self._skipping)
event = wmdocklib.getEvent()
@ -257,7 +257,7 @@ class PywmHDMon:
mounted = True
except NotMounted:
mounted = False
except OSError, e:
except OSError as e:
return
if mounted:
if action == 'mount':
@ -282,7 +282,7 @@ class PywmHDMon:
hdData = self.getHdInfo(path)
except NotMounted:
hdData = (0, 0)
except OSError, e:
except OSError as e:
sys.stderr.write(
"Can't get hd data from %s: %s\n" % (path, str(e)))
hdData = (0, 0)
@ -313,7 +313,7 @@ def parseCommandLine(argv):
'skipconf=','font=', 'debug']
try:
opts, nonOptArgs = getopt.getopt(argv[1:], shorts, longs)
except getopt.GetoptError, e:
except getopt.GetoptError as e:
sys.stderr.write('Error when parsing commandline: ' + str(e) + '\n')
sys.stderr.write(usage)
sys.exit(2)
@ -406,7 +406,7 @@ def main():
configFile = os.path.expanduser(configFile)
fileConfig = wmdocklib.readConfigFile(configFile, sys.stderr)
config = fileConfig
for i in clConfig.iteritems():
for i in clConfig.items():
config[i[0]] = i[1]
palette = {}

View File

@ -10,8 +10,7 @@ Licensed under the GNU General Public License.
"""
import sys, time
from wmdocklib import wmoo
devnull = file('/dev/null')
from wmdocklib import wmoo as wmoo
class Application(wmoo.Application):
@ -58,7 +57,7 @@ class Application(wmoo.Application):
def handler(self, num, frame):
if self._expectdying:
print self._expectdying
print(self._expectdying)
self._expectdying -= 1
else:
self.reset()
@ -74,7 +73,7 @@ class Application(wmoo.Application):
self.child = subprocess.Popen(commandline,
stdin =subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=devnull)
stderr=subprocess.DEVNULL)
signal.signal(signal.SIGCHLD, self.handler)
self._flash = 0
self._paused = False
@ -82,26 +81,26 @@ class Application(wmoo.Application):
self._buffering = 1
self._cacheLevel = 0
import fcntl
flags = fcntl.fcntl(self.child.stdout, fcntl.F_GETFL)
fcntl.fcntl(self.child.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)
flags = fcntl.fcntl(self.child.stdin, fcntl.F_GETFL)
fcntl.fcntl(self.child.stdin, fcntl.F_SETFL, flags | os.O_NONBLOCK)
flags = fcntl.fcntl(self.child.stdout, fcntl.F_GETFL)
fcntl.fcntl(self.child.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)
flags = fcntl.fcntl(self.child.stdin, fcntl.F_GETFL)
fcntl.fcntl(self.child.stdin, fcntl.F_SETFL, flags | os.O_NONBLOCK)
def stopPlayer(self):
if self.child:
print self._expectdying
self.child.stdin.write('q')
print(self._expectdying)
self.child.stdin.write(b'q')
self._expectdying += 1
self.child = None
def muteStream(self, event):
if self.child and self._buffering == 0:
self.child.stdin.write('m')
self.child.stdin.write(b'm')
self.putPattern(9*self._muting, 0, 9, 11, 30, 29)
self._muting = 1 - self._muting
def printevent(self, event):
print event
print(event)
def previousRadio(self, event):
if self.currentRadio == 0: self.currentRadio = len(self.radioList)
@ -128,7 +127,7 @@ class Application(wmoo.Application):
def pauseStream(self, event):
if self.child and not self._buffering:
self.child.stdin.write(' ')
self.child.stdin.write(b' ')
self._paused = not self._paused
if self._paused:
self._colour = 1
@ -167,7 +166,7 @@ class Application(wmoo.Application):
import select
[i, o, e] = select.select([self.child.stdout], [], [], 0)
if i:
line = self.child.stdout.read(102400)
line = self.child.stdout.read(102400).decode("utf-8")
self._buffered += line
npos = self._buffered.rfind('\n')+1
rpos = self._buffered.rfind('\r')+1

View File

@ -85,7 +85,7 @@ class PywmSeti:
try:
wmdocklib.addString(s, x, y, digits,
xOffset, yOffset, width, height)
except ValueError, e:
except ValueError as e:
sys.stderr.write('Error when painting string:\n' + str(e) + '\n')
sys.exit(3)
@ -137,7 +137,7 @@ class PywmSeti:
"""
try:
os.kill(pid, 0)
except OSError, e:
except OSError as e:
if e.errno == 1:
return -1
return 0
@ -146,7 +146,7 @@ class PywmSeti:
def openFileRead(self, fileName):
try:
f = file(fileName, 'r')
except IOError, e:
except IOError as e:
sys.stderr.write('Error when opening %s: %s\n' % (fileName, str(e)))
return None
return f
@ -265,7 +265,7 @@ class PywmSeti:
if self._running:
try:
os.kill(self._pid, 15)
except OSError, e:
except OSError as e:
sys.stderr.write(
"Error when ending process: "+str(e)+'\n')
else:
@ -309,7 +309,7 @@ def parseCommandLine(argv):
'indicatorcolor=']
try:
opts, nonOptArgs = getopt.getopt(argv[1:], shorts, longs)
except getopt.GetoptError, e:
except getopt.GetoptError as e:
sys.stderr.write('Error when parsing commandline: ' + str(e) + '\n')
sys.stderr.write(usage)
sys.exit(2)
@ -459,7 +459,7 @@ def main():
# Merge the two configs, let the commandline options overwrite those in the
# configuration file.
config = fileConfig
for i in clConfig.iteritems():
for i in clConfig.items():
config[i[0]] = i[1]
# Get the configurations
setiDir = config.get('setidir')
@ -472,7 +472,7 @@ def main():
setiDir = os.path.expanduser(setiDir)
try:
os.chdir(setiDir)
except OSError, e:
except OSError as e:
sys.stderr.write('Error when accessing seti directory: %s\n' % str(e))
sys.exit(4)
statePath = os.path.join(setiDir, stateFileName)

View File

@ -95,8 +95,8 @@ class PywmSysMon:
Return a tuple with (total_mem, used_mem, buffered_mem, cached_mem).
"""
try:
meminfoFile = file(self._procMeminfo, 'r')
except IOError, e:
meminfoFile = open(self._procMeminfo, 'r')
except IOError as e:
sys.stderr.write("Can't open meminfo file: %s.\n" % str(e))
sys.exit(2)
total = used = free = shared = buffers = cached = theLine = None
@ -105,17 +105,17 @@ class PywmSysMon:
theLine = line
break
if line.startswith('MemTotal:'):
total = long(line.split()[1])
total = int(line.split()[1])
if line.startswith('MemFree:'):
free = long(line.split()[1])
free = int(line.split()[1])
if line.startswith('Buffers:'):
buffers = long(line.split()[1])
buffers = int(line.split()[1])
if line.startswith('Cached:'):
cached = long(line.split()[1])
cached = int(line.split()[1])
if free and total:
used = total - free
if theLine is not None:
parts = [long(x) for x in theLine.split()[1]]
parts = [int(x) for x in theLine.split()[1]]
total, used, free, shared, buffers, cached = parts[:6]
if None in [total, used, buffers, cached]:
sys.stderr.write("Can't find memory information in %s.\n" %
@ -138,13 +138,13 @@ class PywmSysMon:
file. Return the usage in percent.
"""
try:
statFile = file(self._procStat, 'r')
except IOError, e:
statFile = open(self._procStat, 'r')
except IOError as e:
sys.stderr.write("Can't open statfile: %s.\n" % str(e))
sys.exit(2)
line = statFile.readline()
statFile.close()
cpu, nice, system, idle = [long(x) for x in line.split()[1:]][:4]
cpu, nice, system, idle = [int(x) for x in line.split()[1:]][:4]
used = cpu + system
if not self._ignoreNice:
used += nice
@ -161,7 +161,7 @@ class PywmSysMon:
def addString(self, s, x, y):
try:
wmdocklib.addString(s, x, y, digits, xOffset, yOffset, width, height)
except ValueError, e:
except ValueError as e:
sys.stderr.write('Error when painting string:\n' + str(e) + '\n')
sys.exit(3)
@ -244,7 +244,7 @@ def parseCommandLine(argv):
'procmeminfo=', 'ignorenice', 'updatedelay=']
try:
opts, nonOptArgs = getopt.getopt(argv[1:], shorts, longs)
except getopt.GetoptError, e:
except getopt.GetoptError as e:
sys.stderr.write('Error when parsing commandline: ' + str(e) + '\n')
sys.stderr.write(usage)
sys.exit(2)