You are not logged in.

#76 2010-11-12 14:09:15

llawwehttam
Member
From: United Kingdom
Registered: 2010-01-19
Posts: 180
Website

Re: Conky - update notifier in python

I have the last posted python script up and running with no problems there and it looks fine when run in terminal but when run by conky the output seems indented for no apparent reason.

Screenshot: 1289570877.png

Conky code:

${color0}${font OpenLogos:size=19}P${font}${color}${goto 32}${voffset -10}Pacman Updates:
${color0}${execpi 1000  ~/.conkyupdates.py }

Any ideas?

Last edited by llawwehttam (2010-11-12 14:12:37)


NERD in Training :: Please be Gentle tongue

Offline

#77 2010-11-12 19:15:48

hwkiller
Member
Registered: 2009-07-21
Posts: 55

Re: Conky - update notifier in python

Oh my, how have I missed this?
I'll have to update my conky. I did something similar, but in a rather ghetto way (I don't code at all).

I made a */30 minute cronjob that pacman -Sy'd and Qu'd to ~/`date`.update, then I just had conky parse the text file.

This looks much better.

Offline

#78 2010-11-16 05:46:20

singral
Member
Registered: 2009-09-21
Posts: 27

Re: Conky - update notifier in python

marxav wrote:

Try this. 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Description: Python script for notifying archlinux updates.
# Usage: Put shell script with command 'pacman -Sy' into /etc/cron.hourly/
# Conky: e.g. put in conky '${texeci 1800 python path/to/this/file}'
# Author: Michal Orlik <thror.fw@gmail.com>, sabooky <sabooky@yahoo.com>
import re

################################################################################
# SETTINGS - main settings
# set this to True if you just want one summary line (True/False)
brief = False
# number of packages to display (0 = display all)
num_of_pkgs = 5
#show only important packages
onlyImportant = False
########################################

# OPTIONAL SETTINGS
# PACKAGE RATING - prioritize packages by rating
# pkgs will be sorted by rating. pkg rating = ratePkg + rateRepo for that pkg
# pkg (default=0, wildcards accepted)
ratePkg = {
        'kernel*':10,
        'pacman':9,
        'nvidia*':8,
        }
# repo (default=0, wildcards accepted)
rateRepo = {
        'core':5,
        'extra':4,
        'community':3,
        'testing':2,
        'unstable':1,
        }
# at what point is a pkg considered "important"
iThresh = 5
########################################

# OUTPUT SETINGS - configure the output format
# change width of output
width = 37

# if you would use horizontal you possibly want to disable 'block'
horizontally = False
# separator of horizontal layout
separator = ' ---'
# pkg template - this is how individual pkg info is displayed ('' = disabled)
# valid keywords - %(name)s, %(repo)s, %(size).2f, %(ver)s, %(rate)s
pkgTemplate = "%(repo)s/%(name)s %(ver)s"
# important pkg tempalte - same as above but for "important" pkgs
ipkgTemplate = "%(repo)s/%(name)s %(ver)s"
# summary template - this is the summary line at the end
# valid keywords - %(numpkg)d, %(size).2f, %(inumpkg), %(isize).2f, %(pkgstring)s
summaryTemplate = "%(numpkg)d %(pkgstring)s"
# important summary template - same as above if "important" pkgs are found
isummaryTemplate = summaryTemplate + " (${color yellow}/!\ %(isize).2f Mo${color white})"
# pkg right column template - individual pkg right column
# valid keywords - same as pkgTemplate
pkgrightcolTemplate = "$alignr %(size).2f Mo"
# important pkg right column template - same as above but for important pkgs
ipkgrightcolTemplate = pkgrightcolTemplate
# summary right column template - summay line right column
# valid keywords - same as summaryTemplate
summaryrightcolTemplate = "$alignr${color white} Total: %(size).2f Mo${font}"
# important summary right column template - same as above if "important" pkgs are found
isummaryrightcolTemplate = summaryrightcolTemplate
# seperator before summary ('' = disabled)
block = '-' * 12
# up to date msg
u2d = ''
################################################################################

import subprocess
import re

from time import sleep
from glob import glob
from fnmatch import fnmatch

program = []
pkgs = []
url = None

def runpacman():
    """runs pacman returning the popen object"""
    p = subprocess.Popen(['pacman','-Qu'],
            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    return p

def cmpPkgs(x, y):
        """Compares packages for sorting"""
        if x['rate']==y['rate']:
                return cmp(x['size'], y['size'])
        else:
                return x['rate']-y['rate']

if onlyImportant:
        pkgTemplate, pkgrightcolTemplate = '',''

p = runpacman()
 
for line in p.stdout:
    if not line.strip():
        break

    program += line.split()[0::2]
    
for item in program:
    pkg = {}
    desc_path = False
    desc_paths =  glob('/var/lib/pacman/sync/*/%s-*'%item)

    if not desc_path:
        desc_path = desc_paths[0] + '/desc'

    pkg['repo'] = desc_path.split('/')[-3]
    desc = open(desc_path).readlines()
    checkName = 0
    checkSize = 0
    checkVersion = 0
    for index, line in enumerate(desc):
        if line=='%NAME%\n' and checkName == 0:
            pkgName = desc[index+1].strip()
            pkg['name'] = pkgName
            checkName = 1
        if line=='%CSIZE%\n' and checkSize == 0:
            pkgSize = int(desc[index+1].strip())
            pkg['size'] = pkgSize / 1024.0 / 1024
            checkSize = 1
        if line=='%VERSION%\n' and checkVersion == 0:
            pkgVersion = desc[index+1].strip()
            pkg['ver'] = pkgVersion
            checkVersion = 1

    pkgRate = [v for x, v  in ratePkg.iteritems()
            if fnmatch(pkg['name'], x)]
    repoRate = [v for x, v in rateRepo.iteritems()
            if fnmatch(pkg['repo'], x)]
    pkg['rate'] = sum(pkgRate + repoRate)

    pkgs.append(pkg)

# echo list of pkgs
if pkgs:
    summary = {}
    summary['numpkg'] = len(pkgs)
    summary['size'] = sum([x['size'] for x in pkgs])
    if summary['numpkg'] == 1:
        summary['pkgstring'] = 'Maj'
    else:
        summary['pkgstring'] = 'Majs'
    summary['inumpkg'] = 0
    summary['isize'] = 0
    lines = []
    pkgs.sort(cmpPkgs, reverse=True)
    for pkg in pkgs:
        important = False

        if pkg['rate'] >= iThresh:
            summary['isize'] += pkg['size']
            summary['inumpkg'] += 1
            pkgString = ipkgTemplate % pkg
            sizeValueString = ipkgrightcolTemplate % pkg
        else:
            pkgString = pkgTemplate % pkg
            sizeValueString = pkgrightcolTemplate % pkg

        if len(pkgString)+len(sizeValueString)>width:
                pkgString = pkgString[:width-len(sizeValueString)-1]+'...'

        line = pkgString.ljust(width - len(sizeValueString)) + sizeValueString
        line = re.sub("core/", "${color red}[Core]${color white}", line)
        line = re.sub("extra/", "${color green}[Extra]${color white}", line)
        line = re.sub("community/", "${color violet}[Community]${color white}", line)
        line = re.sub("archlinuxfr/", "${color blue}[ArchFr]${color white}", line)
        line = re.sub("testing/", "${color yellow}[Testing]${color white}", line)
        if line.strip():
            lines.append(line)

    if not horizontally:
        separator = '\n'

    if not brief:
        if num_of_pkgs:
            print separator.join(lines[:num_of_pkgs])
        else:
            print separator.join(lines)
        if block:
            print block.rjust(width-2000)


    if summary['inumpkg']:
        overallString = isummaryTemplate % summary
        overallMBString = summaryrightcolTemplate % summary
    else:
        overallString = summaryTemplate % summary
        overallMBString = isummaryrightcolTemplate % summary
    summaryline =  overallString.ljust(width - len(overallMBString)) \
                       + overallMBString
    if summaryline and not horizontally:
        print summaryline
else:
    print u2d

I am using this script to get update list in conky. it works but something is very wrong with printing code i think...

When i run the script from cli i get this output.

[martins@localhost ~]$python2 .conky_notify.py 
${color green}[Extra]${color white}nvidia...$alignr 4.83 Mo
${color green}[Extra]${color white}nvidia...$alignr 4.83 Mo
${color red}[Core]${color white}coreuti...$alignr 1.89 Mo
${color red}[Core]${color white}glib2 2...$alignr 1.39 Mo
${color green}[Extra]${color white}wxgtk ...$alignr 3.82 Mo
${color green}[Extra]${color white}mercur...$alignr 1.33 Mo
${color green}[Extra]${color white}libgph...$alignr 0.98 Mo
${color green}[Extra]${color white}alsa-u...$alignr 0.86 Mo
${color green}[Extra]${color white}xorg-s...$alignr 0.66 Mo
${color green}[Extra]${color white}xproto...$alignr 0.13 Mo
${color green}[Extra]${color white}libxi ...$alignr 0.13 Mo
${color green}[Extra]${color white}xorg-u...$alignr 0.09 Mo
${color green}[Extra]${color white}libgno...$alignr 0.05 Mo
${color green}[Extra]${color white}xorg-x...$alignr 0.02 Mo
${color green}[Extra]${color white}xf86-i...$alignr 0.02 Mo
------------
27 Majs (${color yellow}/!\ 12.95 Mo${color white})$alignr${color white} Total: 22.09 Mo${font}

This is how it looks when i launch it thought conky
001ptf.th.jpg

I managed to do some editing so the text isn't messed up anymore but then i loose all colors.
Could someone who actually knows python check what is wrong?

Offline

#79 2010-11-16 12:22:36

llawwehttam
Member
From: United Kingdom
Registered: 2010-01-19
Posts: 180
Website

Re: Conky - update notifier in python

That is normal for running it in CLI.

I am running a modified script as I don't need the colors.

${color green} and {$alignr} are understood by conky but not by the command line.


NERD in Training :: Please be Gentle tongue

Offline

#80 2010-11-18 02:20:10

singral
Member
Registered: 2009-09-21
Posts: 27

Re: Conky - update notifier in python

well i wrote my own script. It isn't even near as smart as last one but it can show correct colors and doesn't mess up formating(at least for me)
Some code is taken from last script to. And sorry that code looks so bad, 1st time writing something in python. maybe i will make it better if i don't have anything to do

Install is same as previouse scripts

#!/usr/bin/env python2
#
#Lot of code/ideas taken from Michal Orlik <thror.fw@gmail.com>, sabooky <sabooky@yahoo.com>
#conky update script https://bbs.archlinux.org/viewtopic.php?id=37284
#
#rewrote the script because i coudn't understand some parts to their script
#and it was little bit broken on my machine
#and to learn some basic python
#
###How to use:
#1. make script in /etc/cron.hourly/ wich has this command 'pacman -Sy'
#2. in your .conkyrc insert this line '${execpi update_time python2 /path/to/this/script}'
################################
#Config
################################
#
#outputs '-' symbols to conky so you can find max lenght easier 1 - on, 0 - off
check_width = 0
#How many simbols there are in 1 line
lenght = 29
#How many packages to display in conky
package_count = 10
#How much + value packages gain if they are in some reposatory
value_repo = {
  ('core', 4),
  ('extra', 3),
  ('community', 2),
  ('arch-games', 1),
}
#color for each reposatory
color_repo = {
  ('core','red'),
  ('extra','extra'),
  ('community','purple'),
  ('arch-games','pink'),
  ('sumary', 'white'),
}
#value for seperate packages
value_pkg = {
#  ('gtk2',10),
#  ('libsoup', 15)
}


import os
import subprocess
from glob import glob

def calculate_size(size):
  size = float(size)/(1024*1024)
  return round(size,2)

def draw_line(lenght):
  lines = []
  string = ''
  for i in range(lenght):
    string = string + '-'
  print (string)
  
#Get all packages what need updating
p = subprocess.Popen(['pacman','-Quq'],
            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

#remove \n from output and create multi dimension array
#to store information about packages and stores package name
#[0][0] - package name
#[0][1] - reposatory
#[0][2] - download size
#[0][3] - install size
#[0][4] - value
packages = []
for line in p.stdout:
  for col in range(1):
    line = line.lstrip()[0:-1]
    packages.append([line,0,0,0,0])

#gets reposatory/download size/install size from /var/lib/pacman/sync/*
for package in packages:
  desc_path = False
  desc_paths = glob('/var/lib/pacman/sync/*/%s-*'%package[0])
  
  if not desc_path:
    desc_path = desc_paths[0] + '/desc'
  package[1] = desc_path.split('/')[-3]
  pkg_desc = open(desc_path).readlines()
  for index, line in enumerate(pkg_desc):
    if line == '%CSIZE%\n':
      download_size = pkg_desc[index+1].strip()
      package[2] = calculate_size(download_size)
    if line == '%ISIZE%\n':
      install_size = pkg_desc[index+1].strip()
      package[3] = calculate_size(install_size)

#Gets all packages to ignore
pacman_conf = open('/etc/pacman.conf').readlines()
for line in pacman_conf:
  if line[0:9] == 'IgnorePkg':
    ignore_pkg = line.split()

#removes packages to ignore from package list
for pkg in ignore_pkg:
  for i, package in enumerate(packages):
    if package[0] == pkg:
      packages.pop(i)
  
#gets value for all packages depending on repo
for package in packages:
  for repo in value_repo:
    if repo[0] == package[1]:
      package[4] = package[4] + repo[1]

#gets value for all packages dependng on package name
for i in value_pkg:
  for package in packages:
    if package[0] == i[0]:
      package[4] = package[4] + i[1]

#sort by value decrasing
packages.sort(key=lambda test: test[4], reverse=True)

#output this to conky
if check_width == 1:
  draw_line(lenght)
for package in packages[0:package_count]:
  line_left = package[0]
  line_right = str(package[3]) + 'M'
  line_center = lenght - len(line_right);
  
  if len(line_left) > line_center:
    line_left = line_left[0:line_center-4]
    line_left = line_left + '...'
  line_center = line_center - len(line_left)
  space = ''
  for i in range(line_center):
    space = space + ' '
  
  if package[1] == 'core':
    line_left = '${color red}' + line_left + '${color}'
  elif package[1] == 'extra':
    line_left = '${color green}' + line_left + '${color}'
  elif package[1] == 'community':
    line_left = '${color purple}' + line_left + '${color}'
  elif package[1] == 'arch-games':
    line_left = '${color pink}' + line_left + '${color}'
  print (line_left + space + line_right)
count = len(packages)
install_size = 0
download_size = 0
for i in packages:
  install_size = install_size + i[3]
  download_size = download_size + i[2]
line_left = 'Total: ' + str(count)
line_right = str(download_size) + 'M/' + str(install_size) + 'M'
line_center = lenght - len(line_right)
line_center = line_center - len(line_left)
line_left = '${color white}' + line_left + '${color}'
line_right = '${color white}' + line_right + '${color}'
space = ''
for i in range(line_center):
  space = space + ' '
draw_line(lenght)
print (line_left + space + line_right)

screen with how it looks:
001w.th.png

Last edited by singral (2010-11-19 21:38:00)

Offline

#81 2010-12-08 20:47:50

Ben9250
Member
From: Bath - England
Registered: 2010-06-10
Posts: 208
Website

Re: Conky - update notifier in python

I just put a crontab for sudo pacman -Sy ever 30 mins, and then put the script with the conky files in /etc/conky/ and made sure it was executable, and added an entry in my conky.conf for it, but it keeps telling me my system is up to date, but if I run sudo pacman -Qu I get 16 packages listed. Does anyone have any idea why this might be? If i run the script from the terminal I get no errors, just a message telling my my system is up to date.

Cheers.


"In England we have come to rely upon a comfortable time-lag of fifty years or a century intervening between the perception that something ought to be done and a serious attempt to do it."
  - H. G. Wells

Offline

#82 2012-01-05 06:51:55

Chr|s
Member
From: New York State, USA
Registered: 2012-01-04
Posts: 14

Re: Conky - update notifier in python

I thought using pacman -Sy is wrong to do? not really suppose to do this, can screw up your system?

Offline

#83 2012-01-05 06:58:56

bernarcher
Forum Fellow
From: Germany
Registered: 2009-02-17
Posts: 2,272

Re: Conky - update notifier in python

Chr|s, why should -Sy be wrong? All it does is synchronizing the package databases making sure to keep them up to date. Please read man pacman again.

Also, this thread is really old now. Closing.


To know or not to know ...
... the questions remain forever.

Offline

Board footer

Powered by FluxBB