You are not logged in.

#2826 2016-10-07 20:09:43

Stencon281
Member
Registered: 2016-09-21
Posts: 40

Re: Post your handy self made command line utilities

Trilby wrote:
Sachiko wrote:

This is to make it seem like the script is contemplating something...

You've previously worked for Microsoft?

Do I laugh or cry?

Offline

#2827 2016-10-08 12:15:11

basica
Member
From: Australia
Registered: 2012-10-31
Posts: 217

Re: Post your handy self made command line utilities

After doing a good bunch of LFS PKGBUILDS manually, I decided it was time to automate the process a tiny bit. It's not perfect, but it is "good enough"; for my purposes at least with this python script. Critiques are of course are welcome.

import os, sys
dl_file = sys.argv[1]

# get the filename from the url download
i = dl_file.rfind("/")
temp = dl_file[i+1:]
# get the package name and version, discard the extension
fname = temp.split(".tar.")
# split the package name from the package version
i = fname[0].rfind("-")
pkgname = fname[0][:i]
pkgver = fname[0][i+1:]
# generate a new generic url download from the above variables
url = dl_file.replace(pkgname,"$pkgname").replace(pkgver,"$pkgver")

# create the PKGBUILD with the data generated above

os.makedirs(pkgname)
pkg_file = open(pkgname + '/PKGBUILD','w')
pkg_data = "# Maintainer: something@somewhere.com\n\n"
pkg_data += "pkgname=" + pkgname + "\n"
pkg_data += "pkgver=" + pkgver + "\n"
pkg_data += "pkgrel=1" + "\n"
pkg_data += "pkgdesc='Description goes here'" + "\n"
pkg_data += "arch=('x86_64')" + "\n"
pkg_data += "license=('GPL2')" + "\n"
pkg_data += 'source=("'+ url +'")' + "\n"
pkg_data += "sha512sums=('')" + "\n\n"
pkg_data += 'build(){\n\tcd "$srcdir/$pkgname-$pkgver"\n}' + "\n"
pkg_data += 'package(){\n\tcd "$srcdir/$pkgname-$pkgver"\n\tmake DESTDIR=$pkgdir install\n}'
pkg_file.write(pkg_data)
pkg_file.close()  

Last edited by basica (2016-10-08 12:15:51)

Offline

#2828 2016-10-09 02:16:29

eschwartz
Fellow
Registered: 2014-08-08
Posts: 4,097

Re: Post your handy self made command line utilities

snakeroot wrote:

This is brilliant! How have I lived without this? Since I found the documentation is a little opaque, here's what I did and plan to do.

BACKGROUND

Single user system, with all AUR packages held in their respective build directories and installed via "pacman -U".

STEPS

1. Create new "/home/<user>/packages" directory
2. Move all current AUR packages into "/home/<user>/packages" directory
3. Edit "/etc/makepkg.conf" to add the line

PKGDEST=/home/<user>/packages

4. Add the following new lines to "/home/<user>/.bashrc":

alias aurupdate="repo-add -n -R /home/chris/packages/AUR.db.tar.xz /home/chris/packages/*.pkg.tar.xz"
alias aurinstall="sudo pacman -Syu $(pacman -Sl AUR | grep -v installed | cut -d ' ' -f 2)"

5. source .bashrc and run aurupdate
6. Going forward, after building new AUR packages run aurinstall

Does this make sense? Do you have any suggestions on better ways to do this?

I do something similar...

I have PKGDEST set to /var/cache/pacman/custom in makepkg.conf and added it as a CacheDir in my pacman.conf
I also use the following script to update my custom repo, which allows me to specify the packages to update in repo-add (if specified, it is faster than trying everything), allows me to easily remove something if necessary, and excludes kernel updates (because I don't want to automatically replace my running kernel + modules, see FS#16702):

#!/bin/bash

shopt -s extglob

cd /var/cache/pacman/custom/

act="add"
force="-n"

while [[ "${1}" != "" ]]; do
    case "${1}" in
        -r|--remove)
            act="remove"
            ;;
        -f|--force)
            force=""
            ;;
        -k|--kernel)
            upgrade_kernels=1
            ;;
        *)
            break
            ;;
    esac
    shift
done

if [[ "${1}" != "" ]]; then
    while [[ "${1}" != "" ]]; do
        if [[ "${act}" = "remove" ]]; then
            packages+=("${1}")
        else
            packages+=("${1}-+([a-z0-9.:_+])-[0-9]-@(any|i686|x86_64).pkg.tar.xz")
        fi
        shift
    done
else
    packages=(*.pkg.tar.xz)
fi

for pkg in "${packages[@]}"; do
    if [[ "${pkg}" =~ ^linux-?.* ]]; then
        kernel_pkgs+=("${pkg}")
    else
        regular_pkgs+=("${pkg}")
    fi
done

if [[ "${upgrade_kernels}" != "" ]]; then
    repo-${act} ${force} custom.db.tar.gz ${kernel_pkgs[@]}
else
    repo-${act} -R ${force} custom.db.tar.gz ${regular_pkgs[@]}
fi

My pacman.conf lists the custom repo and includes /etc/pacman.d/nocustom.conf with the main part of my pacman configuration. I have yaourt set to use that instead -- so yaourt will still treat custom packages as foreign packages and get them from the AUR.

Last edited by eschwartz (2016-10-11 04:17:29)


Managing AUR repos The Right Way -- aurpublish (now a standalone tool)

Offline

#2829 2016-10-09 02:17:06

eschwartz
Fellow
Registered: 2014-08-08
Posts: 4,097

Re: Post your handy self made command line utilities

basica wrote:

After doing a good bunch of LFS PKGBUILDS manually, I decided it was time to automate the process a tiny bit. It's not perfect, but it is "good enough"; for my purposes at least with this python script. Critiques are of course are welcome.

import os, sys
dl_file = sys.argv[1]

# get the filename from the url download
i = dl_file.rfind("/")
temp = dl_file[i+1:]
# get the package name and version, discard the extension
fname = temp.split(".tar.")
# split the package name from the package version
i = fname[0].rfind("-")
pkgname = fname[0][:i]
pkgver = fname[0][i+1:]
# generate a new generic url download from the above variables
url = dl_file.replace(pkgname,"$pkgname").replace(pkgver,"$pkgver")

# create the PKGBUILD with the data generated above

os.makedirs(pkgname)
pkg_file = open(pkgname + '/PKGBUILD','w')
pkg_data = "# Maintainer: something@somewhere.com\n\n"
pkg_data += "pkgname=" + pkgname + "\n"
pkg_data += "pkgver=" + pkgver + "\n"
pkg_data += "pkgrel=1" + "\n"
pkg_data += "pkgdesc='Description goes here'" + "\n"
pkg_data += "arch=('x86_64')" + "\n"
pkg_data += "license=('GPL2')" + "\n"
pkg_data += 'source=("'+ url +'")' + "\n"
pkg_data += "sha512sums=('')" + "\n\n"
pkg_data += 'build(){\n\tcd "$srcdir/$pkgname-$pkgver"\n}' + "\n"
pkg_data += 'package(){\n\tcd "$srcdir/$pkgname-$pkgver"\n\tmake DESTDIR=$pkgdir install\n}'
pkg_file.write(pkg_data)
pkg_file.close()  

Build functions are not mandatory...

So this basically just takes a download url and tries to extract a pkgname-pkgver from it, then assumes the software can be built with make install? Should work okay, except that $pkgdir needs to be quoted just like srcdir... also, you might as well tell sha512sums to SKIP itself since fr auto-generated self-used PKGBUILDs integrity checks aren't really useful (and they certainly aren't supplying security).


Managing AUR repos The Right Way -- aurpublish (now a standalone tool)

Offline

#2830 2016-10-09 03:36:35

basica
Member
From: Australia
Registered: 2012-10-31
Posts: 217

Re: Post your handy self made command line utilities

Eschwartz wrote:

Build functions are not mandatory...

So this basically just takes a download url and tries to extract a pkgname-pkgver from it, then assumes the software can be built with make install? Should work okay, except that $pkgdir needs to be quoted just like srcdir... also, you might as well tell sha512sums to SKIP itself since fr auto-generated self-used PKGBUILDs integrity checks aren't really useful (and they certainly aren't supplying security).

I am not using these PKGBUILDS in this form; most of them need to have additional things added to the build and package functions. It's just to save me time rewriting things from scratch all the time or copying another PKGBUILD. After creating this I found you can create templates for makepkg which might make this redundant, but I'll need to take a look at it to see how it works first. Also, thanks for the note about the pkgdir variable. I'll will update it.

Offline

#2831 2016-10-09 04:19:47

eschwartz
Fellow
Registered: 2014-08-08
Posts: 4,097

Re: Post your handy self made command line utilities

Same difference. smile

Anyway, makepkg-template is really meant for PKGBUILDs that contain verbatim code which sometimes needs to be updated... in multiple PKGBUILDs.
It is like using m4_include() for your PKGBUILD.in and of course you need to manually add the template call then run makepkg-template which I don't think is what you had in mind.


Also, I would use a formatted text block for the PKGBUILD as it is a lot more readable, e.g.:

#!/usr/bin/python

pkgname='somepackage'
pkgver='1.2.3'
url='http://example.com/somepackage-1.2.3.tar.gz'

PKGBUILD='''
# Maintainer: something@somewhere.com

pkgname={PKGNAME}
pkgver={PKGVER}
pkgrel=1
pkgdesc='Description goes here'
arch=('x86_64')
license=('GPL2')
source=("{URL}")
sha512sums=('SKIP')

build(){{
	cd "$srcdir/$pkgname-$pkgver"
}}
package(){{
	cd "$srcdir/$pkgname-$pkgver"
	make DESTDIR="$pkgdir" install
}}
'''.strip()

print(PKGBUILD.format(PKGNAME=pkgname, PKGVER=pkgver, URL=url))

Note that actual brackets in the resulting formatted text must be doubled.
The opening and closing triple-quotes are on their own lines, the resulting leading/trailing newlines get stripped though so it's all good. smile

Last edited by eschwartz (2016-10-09 04:33:40)


Managing AUR repos The Right Way -- aurpublish (now a standalone tool)

Offline

#2832 2016-10-09 04:32:47

basica
Member
From: Australia
Registered: 2012-10-31
Posts: 217

Re: Post your handy self made command line utilities

Eschwartz wrote:

Same difference. smile

Anyway, makepkg-template is really meant for PKGBUILDs that contain verbatim code which sometimes needs to be updated... in multiple PKGBUILDs.
It is like using m4_include() for your PKGBUILD.in and of course you need to manually add the template call then run makepkg-template which I don't think is what you had in mind.


Also, I would use a formatted text block for the PKGBUILD as it is a lot more readable, e.g.:

...

Note that actual brackets in the resulting formatted text must be doubled.

That is very handy. I've been using python for ages and never knew about that. Cheers smile

Offline

#2833 2016-11-05 14:26:12

parchd
Member
Registered: 2014-03-08
Posts: 421

Re: Post your handy self made command line utilities

After setting up encryption on my system, I was planning on using chkboot (see AUR), but I figured if I want my system to be secure I should understand how it works. To that end I tried writing my own equivalent (which I will probably end up using).
I call it "tamper". Here it is in case anyone fancies a look, or better still wants to give feedback:

#!/bin/bash

TAMPER_DIR="/var/lib/tamper/"
BOOT_LOG="$TAMPER_DIR/boot"
MBR_LOG="$TAMPER_DIR/mbr"

MBR_DEVICE="/dev/vda"

function get_mbr(){
        dd if=$MBR_DEVICE of=/tmp/mbr.bak bs=512 count=1
}

function get_boot(){
        tar -c /boot --exclude /boot/grub/grubenv -f /tmp/boot.bak
}

function check_mbr(){
        if [ -e $MBR_LOG ]; then
                get_mbr &&
                sha512sum -c <(tail -n1 $MBR_LOG)
        else
                echo "'$MBR_LOG' does not exist" >&2
                return 1
        fi
}

function check_boot(){
        if [ -e $BOOT_LOG ]; then
                get_boot &&
                sha512sum -c <(tail -n1 $BOOT_LOG)
        else
                echo "'$BOOT_LOG' does not exist" >&2
                return 1
        fi
}

function check() {
        check_mbr && 
        rm /tmp/mbr.bak || echo "MBR did not validate!" >&2
        check_boot &&
        rm /tmp/boot.bak || echo "/boot did not validate!" >&2
}

function update(){
        mkdir -p $TAMPER_DIR &&
        if ! check_mbr; then
                if ! [ -e /tmp/mbr.bak ]; then
                        get_mbr
                fi
                sha512sum /tmp/mbr.bak >> $MBR_LOG
                mv /tmp/mbr.bak $TAMPER_DIR
                echo "Updated mbr"
        else
                echo "MBR already up to date"
                rm /tmp/mbr.bak
        fi

        if ! check_boot; then
                if ! [ -e /tmp/boot.bak ]; then
                        get_boot
                fi
                sha512sum /tmp/boot.bak >> $BOOT_LOG
                mv /tmp/boot.bak $TAMPER_DIR
                echo "Updated boot"
        else
                echo "/boot already up to date"
                rm /tmp/boot.bak
        fi
}

case $1 in
        "--help" ) ;&
        "-h" )
                echo "Options: --update (-u): update the tamper database"
                ;;
        "--update" ) ;&
        "-u" )
                update &&
                echo "Updated"
                ;;
        "--check" ) ;&
        "-c" )
                check
                ;;
esac

exit $?

Offline

#2834 2016-11-06 16:04:15

blippy
Member
Registered: 2010-11-18
Posts: 38

Re: Post your handy self made command line utilities

I have a script which I call "parf":

#!/usr/bin/env bash

RC=$HOME/.parfrc

function print_help {
cat <<EOF
Prints out the content of the RC file ($RC), with newlines replaced by colons
-c add current directory to RC file
-e edit RC file using default editor
-h this help
-s SEP specifiy separator
EOF
}

SEP=':'

while getopts "cehs:" opt
do
    case $opt in
        c) echo `pwd` >> $RC ;;
        e) $EDITOR $RC ;;
        h) print_help ;;
        s) SEP=$OPTARG ;;
        *) echo "Unrecognised argument: $opt" ; exit 1 ;;
    esac
done


# construct a complete path
function prpath {
    if [ -f $RC ]; then
        local res=
        while read line
        do
            #echo inpu $line
            if [ -d "$line" ]; then
                res="$line$SEP$res"
                #echo $line
                #echo res so far "$res"
            fi
        done < <(tac $RC)
        echo "$res"
    fi
}

prpath

It is a PATH editor. PATHs are stored in ~/.parfc, one per line. If you want to add the current dir to the PATH, type parf -c. If you want to see the path that is created, type parf. If you want to edit your path configuration file, type parf -e. Don't need the path any more? Just parf -e and delete the offending line. You will need to set the EDITOR variable in order to edit the path.

Add parf somewhere bash can see it, and in your .bashrc add the line
PATH=`parf`$PATH

You also need to start a new bash shell for the changes to take effect.

It saves me a lot of hassle.

Offline

#2835 2016-11-06 16:14:59

blippy
Member
Registered: 2010-11-18
Posts: 38

Re: Post your handy self made command line utilities

Something I'm getting into is bosh (browseable output shell), available in AUR.

The idea behind it is that you provide a configuration file specifiying a command to run, and action keys. bosh runs the command. You can select an output line, press an action key, and bosh runs the action for that key, on that line.

The world's your lobster as to what you can get it to do. A canned script is called bops, which prints the running processes. Select the process you want to kill, and type 'k'. Nifty.

I am using it at the moment to list files in a certain directory. I can highlight the file I am interested in, and select "v" to view the file contents.

Limitless possibilities.

Offline

#2836 2016-11-06 18:02:08

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 30,330
Website

Re: Post your handy self made command line utilities

bosh sounds interesting, but the PKGBUILD for it is ridiculous.  There are countless things wrong, but the troubling issues are the use of "unknown" license when it is very clearly GPL2 and the failure to properly use the configure script to install in /usr.  I'll post a proper PKGBUILD in the comments for that package momentarily.


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#2837 2016-11-06 22:07:05

Alad
Wiki Admin/IRC Op
From: Bagelstan
Registered: 2014-05-04
Posts: 2,418
Website

Re: Post your handy self made command line utilities

#2833, #2834: Obligatory reference to shellcheck.net …


Mods are just community members who have the occasionally necessary option to move threads around and edit posts. -- Trilby

Offline

#2838 2016-11-06 22:25:49

parchd
Member
Registered: 2014-03-08
Posts: 421

Re: Post your handy self made command line utilities

Alad wrote:

#2833, #2834: Obligatory reference to shellcheck.net …

Was there a specific critique?
I'd already put mine through shellcheck and had no issues detected, but I don't usually write more than one-liners so improvement suggestions on style (or otherwise) are more than welcome.

Offline

#2839 2016-11-23 12:54:45

kokoko3k
Member
Registered: 2008-11-14
Posts: 2,421

Re: Post your handy self made command line utilities

Simple script i've bound to Alt-shift-F11 to switch nvidia's ForceFullCompositionPipeline state (i know, too many sed)

nvidia.compositionpipeline.switch.sh

#!/bin/bash
killall aosd_cat
if nvidia-settings -t -q CurrentMetaMode|grep 'ForceCompositionPipeline=On' &>/dev/null ; then
    nvidia.compositionpipeline.disable.sh &
    echo "FFCP=OFF" | aosd_cat -n "Sans Bold 15"  -x 0 -y 0 -p 0 -t 0 -b 255 -s 255 -d 10 -R yellow  -u 5000 &
    echo "FFCP=OFF" | aosd_cat -n "Sans Bold 15"  -x 0 -y 0 -p 2 -t 0 -b 255 -s 255 -d 10 -R yellow  -u 5000 &
        else
    nvidia.compositionpipeline.enable.sh &
    echo "FFCP=ON" | aosd_cat -n "Sans Bold 15"   -x 0 -y 0 -p 0 -t 0 -b 255 -s 255 -d 10 -R "#99ccff"  -u 5000 &
    echo "FFCP=ON" | aosd_cat -n "Sans Bold 15"   -x 0 -y 0 -p 2 -t 0 -b 255 -s 255 -d 10 -R "#99ccff"  -u 5000 &
fi

nvidia.compositionpipeline.enable.sh

#/bin/bash
sh -c "nvidia-settings --assign CurrentMetaMode=\"$(nvidia-settings -t -q CurrentMetaMode |tr -d "\n"|sed 's/ViewPortIn=/ForceFullCompositionPipeline=On, ViewPortIn=/g'|sed 's/.*:://'|sed 's/^ *//;s/ *$//')\""

nvidia.compositionpipeline.disable.sh

#!/bin/bash
sh -c "nvidia-settings --assign CurrentMetaMode=\"$(nvidia-settings -t -q CurrentMetaMode |tr -d "\n"|sed 's/.*:://'|sed 's/^ *//;s/ *$//'|sed "s/CompositionPipeline=On/CompositionPipeline=Off/g")\""

Help me to improve ssh-rdp !
Retroarch User? Try my koko-aio shader !

Offline

#2840 2016-11-23 23:07:34

Mladia
Member
Registered: 2016-04-30
Posts: 59

Re: Post your handy self made command line utilities

I have a script that gives me the current weather forecast.

It finds the city by IP and then send query to yahoo.

getWeather.sh

#!/bin/bash


place=$(curl -s http://whatismycountry.com/ | sed -n 's|.*> *\(.*\)</h3>|\1|p')

if ! [ -z  $@  ]
then
	place=$@
fi

echo "Location is $place"

qu="select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\"$place\") and u='c'"



curl -s https://query.yahooapis.com/v1/public/yql -d q="$qu" -o ~/.cache/weather.xml

#for which hour?
grep "yweather:forecast" ~/.cache/weather.xml | grep -o "<title>Conditions [^\"]*</title>" | grep -o "[0-9]*:[0-9]* [A-Z][A-Z]"

#print temperature
grep "yweather:condition" ~/.cache/weather.xml | grep -o "temp=\"[^\"]*\"" | grep -o "\"[^\"]*\"" | grep -o "[^\"]*"

Offline

#2841 2016-11-24 08:24:52

Docbroke
Member
From: India
Registered: 2015-06-13
Posts: 1,438

Re: Post your handy self made command line utilities

You will like "curl wttr.in"

Offline

#2842 2016-11-24 13:52:22

Awebb
Member
Registered: 2010-05-06
Posts: 6,610

Re: Post your handy self made command line utilities

Docbroke wrote:

You will like "curl wttr.in"

We were unable to find your location, so we have brought you to Oymyakon, one of the coldest permanently inhabited locales on the planet.

Brrrrr!

Offline

#2843 2016-11-24 15:59:19

Docbroke
Member
From: India
Registered: 2015-06-13
Posts: 1,438

Re: Post your handy self made command line utilities

Awebb wrote:
Docbroke wrote:

You will like "curl wttr.in"

We were unable to find your location, so we have brought you to Oymyakon, one of the coldest permanently inhabited locales on the planet.

Brrrrr!

wttr.in uses ip address to identify location, if that fail you may try

 curl wttr.in/"yourlocation"

Offline

#2844 2016-12-06 11:06:27

kokoko3k
Member
Registered: 2008-11-14
Posts: 2,421

Re: Post your handy self made command line utilities

Another workaround for an unfixed plasma bug.
Since sometimes it does not update panels when compositing is switched off, it happens that i when i play games, i'm often in late, because i see the un-updated clock on the other head (i play with no compositing).
Fortunately, the Xrender Backend does not impact performance and nvidia ForceCompositingPipeline is able to do vsync even when using Xrender, so here is a script i bound to alt+shift+F10 that switches compositor type and notify it via OSD:

#!/bin/bash
killall aosd_cat
Current_compositing=$(qdbus org.kde.KWin /Compositor compositingType)

function reconfigure {
    qdbus org.kde.KWin /KWin reconfigure
    sleep 0.2
    qdbus org.kde.KWin /Compositor suspend
    sleep 0.2
    qdbus org.kde.KWin /Compositor resume   
}

function OSD {
    echo "$1" | aosd_cat -n "Sans Bold 15"   -x 0 -y 0 -p 0 -t 0 -b 255 -s 255 -d 10 -R "#99ccff"  -u 5000 &
    echo "$1" | aosd_cat -n "Sans Bold 15"   -x 0 -y 0 -p 2 -t 0 -b 255 -s 255 -d 10 -R "#99ccff"  -u 5000 &

}

if [ $Current_compositing = "gl2" ] ; then
    echo Current:gl2
    echo Switch :xrender
    kwriteconfig5 --file kwinrc --group Compositing --key Backend XRender
    OSD "Compositor: OpenGL -> xrender"
    reconfigure
    exit
fi

if [ $Current_compositing = "xrender" ] ; then
    echo Current:xrender
    echo Switch :none
    OSD "Compositor: xrender -> Disabled"
    qdbus org.kde.KWin /Compositor suspend
    exit
fi

if [ $Current_compositing = "none" ] ; then
    echo Current:none
    echo Switch :gl2
    kwriteconfig5 --file kwinrc --group Compositing --key Backend OpenGL
    OSD "Compositor: disabled -> OpenGL"
    reconfigure
    exit
fi

Help me to improve ssh-rdp !
Retroarch User? Try my koko-aio shader !

Offline

#2845 2016-12-25 00:17:05

Roken
Member
From: South Wales, UK
Registered: 2012-01-16
Posts: 1,281

Re: Post your handy self made command line utilities

I thought I'd already posted this, but I can't find it. Particularly handy for DEs such as XFCE. Possibly the most simplistic music player GUI ever. One button, "Stop". Double click (at least in xfce) starts it. The button lands under your mouse pointer. If you let it play through, it goes away quietly.  Needs mpg123 to be installed.

EDIT: I wrote this a while ago. It seems to handle video via vlc, too. I forgot about that.

Python script:

#!/usr/bin/env python

import sys
import os
import argparse
import gobject
import multiprocessing
import threading
import time

try:
	import pygtk
	pygtk.require("2.0")
except:
	pass
try:
	import gtk
	import gtk.glade
except:
	sys.exit(1)
	
gtk.gdk.threads_init()

playing = 0
filename = ""
child = 0

class Listener(gobject.GObject):
	__gsignals__ = {
		'finished': (gobject.SIGNAL_RUN_LAST,
					gobject.TYPE_NONE,
					())
	}

	def __init__(self, queue):
		gobject.GObject.__init__(self)
		self.queue = queue

	def go(self):
		while True:
			data = self.queue.get()
			if data[1]=="finished":
				pass
			self.emit("finished")
			return

gobject.type_register(Listener)

class Worker():
	def __init__(self, queue):
		self.queue = queue

	def go(self):
		command = 'mpg123 -q "'+ns.filename+'"'
		done = os.system (command)
		self.queue.put((1.0, "finished"))

class KillTune:
	def __init__(self):
		command = "killall mpg123"
		child = os.popen(command)
		return None

		
	def run(self):
		os.system (command)
		return True


class PlayerWindow:
	"""This is an mpg123 player application"""

	def __init__(self):

		self.gladefile = "/usr/share/pythonmpg123/project2.glade"
		self.wTree = gtk.glade.XML(self.gladefile) 
		
		self.window = self.wTree.get_widget("window1")
		if (self.window):
			self.window.connect("destroy", gtk.main_quit)
			
		dic = {
			"on_button2_clicked" : self.button2,
		}
		self.wTree.signal_autoconnect(dic)
		queue = multiprocessing.Queue()
		worker = Worker(queue)
		listener = Listener(queue)
		listener.connect("finished",self.playerFinished)
		self.process = multiprocessing.Process(target=worker.go, args=())
		self.process.start()
		thread = threading.Thread(target=listener.go, args=())
		thread.start()

		
	def playerFinished(self,widget):
		if self.process==None:
			raise RuntimeError("No worker process started")
		self.process.join()
		self.process = None
		gtk.main_quit()

	def button2(self,widget):
		playing = KillTune()
							
if __name__ == "__main__":
	parser = argparse.ArgumentParser(add_help=False)
	parser.add_argument('-t', dest="filename")
	KillTune()
	ns = parser.parse_args()
	pw = PlayerWindow()
	gtk.main()

And the script to launch it. You need to correct the paths.

#!/bin/bash

IFS="
"
chkname=(`echo ${1%.*}`)
chkname=$chkname.cdg
if [ -f $chkname ]; then
	vlc $1
else
	python2./PATH/TO/mp123.py -t "$1"
fi

EDIT: The glade file would probably be useful, too

<?xml version="1.0" standalone="no"?> <!--*- mode: xml -*-->
<!DOCTYPE glade-interface SYSTEM "http://glade.gnome.org/glade-2.0.dtd">

<glade-interface>

<widget class="GtkWindow" id="mp123">
  <property name="width_request">83</property>
  <property name="height_request">32</property>
  <property name="visible">True</property>
  <property name="title" translatable="yes">Mpg123 Player</property>
  <property name="type">GTK_WINDOW_TOPLEVEL</property>
  <property name="window_position">GTK_WIN_POS_MOUSE</property>
  <property name="modal">False</property>
  <property name="resizable">False</property>
  <property name="destroy_with_parent">False</property>
  <property name="decorated">False</property>
  <property name="skip_taskbar_hint">False</property>
  <property name="skip_pager_hint">False</property>
  <property name="type_hint">GDK_WINDOW_TYPE_HINT_NORMAL</property>
  <property name="gravity">GDK_GRAVITY_NORTH_WEST</property>
  <property name="focus_on_map">True</property>
  <property name="urgency_hint">False</property>

  <child>
    <widget class="GtkHBox" id="hbox1">
      <property name="visible">True</property>
      <property name="homogeneous">False</property>
      <property name="spacing">0</property>

      <child>
	<widget class="GtkButton" id="button2">
	  <property name="visible">True</property>
	  <property name="can_focus">True</property>
	  <property name="label" translatable="yes">Stop</property>
	  <property name="use_underline">True</property>
	  <property name="relief">GTK_RELIEF_NORMAL</property>
	  <property name="focus_on_click">True</property>
	  <signal name="clicked" handler="on_button2_clicked" last_modification_time="Tue, 22 May 2012 18:00:48 GMT"/>
	</widget>
	<packing>
	  <property name="padding">0</property>
	  <property name="expand">True</property>
	  <property name="fill">True</property>
	</packing>
      </child>
    </widget>
  </child>
</widget>

</glade-interface>

Last edited by Roken (2016-12-25 08:22:45)


Ryzen 5900X 12 core/24 thread - RTX 3090 FE 24 Gb, Asus Prime B450 Plus, 32Gb Corsair DDR4, Cooler Master N300 chassis, 5 HD (1 NvME PCI, 4SSD) + 1 x optical.
Linux user #545703

/ is the root of all problems.

Offline

#2846 2016-12-27 06:08:50

cryzed
Member
Registered: 2010-05-11
Posts: 14

Re: Post your handy self made command line utilities

I made quite a few, most interestingly probably:

* aur-auto-vote (Automates voting and unvoting for installed AUR packages.)
* backup-system (This is backup solution that works for me: I am aware it is not perfect.)
* defaults (Inspect the original version of files belonging to installed packages.)
* hotstrings (AutoKey-like functionality in a very lightweight manner.)

and maybe also:
* provides (List executables installed into a PATH directory by a given package.)
* youtuber (Small utility that helps keeping a YouTube video collection up-to-date.)
* ShareY (Small command-line utility to easily take screenshots, upload them to a hoster and copy the URL to the clipboard.)

Click the links for a more in-depth explanation for each entry.

Last edited by cryzed (2016-12-27 06:09:40)

Offline

#2847 2016-12-30 06:09:19

UsrCletus
Member
Registered: 2016-12-30
Posts: 4

Re: Post your handy self made command line utilities

A Script to download and install the yaourt package:

#!/bin/bash
#Simple script to install yaourt on arch written by Cletus

installDir="/home/$(whoami)/builds/"

function install {
	cd $installDir
	git clone https://aur.archlinux.org/package-query.git
	cd package-query
	makepkg -sri
	cd $installDir
	git clone https://aur.archlinux.org/yaourt.git
	cd yaourt
	makepkg -sri	
}

function checkDependencies {
        pacDependencies="tar curl git yajl diffutils gettext sudo"
        pacMissing=""
	missingCount=0
	echo "Checking dependencies..."
	echo
        for package in `echo $pacDependencies`
        do
                hasPackage=`pacman -Q $package 2>&1|grep "not found"|wc -l`
                if [ $hasPackage -eq 0 ]
                then
                        echo "Found: $package"
		else
			pacMissing="$pacMissing $package"
			missingCount=$(expr $missingCount + 1)
                fi
        done
	base=$(pacman -Qs base-devel)
        if [[ $base == "" ]]; then
		pacMissing="$pacMissing $package"
                missingCount=$(expr $missingCount + 1)
	fi
	if [ $missingCount -gt 0 ]
	then
		echo 
		echo "----------------------------------------"
		echo "You are missing the following packages: "
        	echo "----------------------------------------"
        	for missingPackage in $pacMissing
        	do
        		echo $missingPackage
        	done
		echo
	        read -p "Would you like me to install them automagically?(y/n): " -n 1 -r
		echo
		if [[ $REPLY =~ ^[Yy]$ ]]
		then
			sudo pacman -S $pacMissing
		else
			echo "Ok. To install them yourself do: "
			echo "sudo pacman -S $pacMissing"
			echo "Exiting.."
			echo 
			exit 1
		fi
	fi
	choose_dir
}

function verify_choice {

	wasVerified=0

	if [ ! -d "$installDir" ]
	then
		echo "Install directory doesn't exist, attempting to create it..."
		mkdir -p $installDir 2>/dev/null
	else
		echo "Install directory exists, checking permissions."
	fi

	if [ -d "$installDir" ]
	then
		badtouch="badtouch"
		touchfile="$installDir$badtouch"
        	touch $touchfile 2>/dev/null
        	if [ -a "$touchfile" ]
        	then    
        		echo "OK"
        		rm -fv $touchfile 2>/dev/null
			wasVerified=$(expr $wasVerified + 1)
		else
			echo "Error attempting to create $installDir, please ensure you have write permissions before continuing."
			exit 1
        	fi
	fi


	if [ $wasVerified -gt 0 ]
	then
		install
	fi

}

function choose_dir {

	read -p "Install directory[$installDir]?:  " -r
	echo
	if [[ $REPLY == "" ]]
	then
		read -p "Are you ready to install?(y/n): " -n 1 -r
		if [[ $REPLY =~ ^[Yy]$ ]]
		then
			verify_choice
		fi
	else

        	read -p "You chose $installDir, is this correct (y/n)?: " -n 1 -r
        	echo
        	if [[ $REPLY =~ ^[Yy]$ ]]
        	then
			verify_choice
        	else
        		exit 1
        	fi
	fi

}

function init {

        echo
        echo "==================================="
        echo "==Yaourt Install Script by Cletus=="
        echo "==================================="
        echo

	#Make sure user is NOT root
	if [[ $EUID -eq 0 ]]; then
	   echo "This script must NOT be run as root."
	   echo "However, you must be in the sudoers file."
	   exit 1
	fi

	#Check to make sure they have the 'wheel' group
	hasWheel=$(grep $(whoami) /etc/group|grep wheel |wc -l)

	if [ $hasWheel -lt 1 ]
	then
		echo "You do not appear to be part of the wheel group."
		echo "To add yourself, escalate to root and run the following: "
		echo "usermod -aG wheel $(whoami)"
		echo "You may also need to give the wheel group sudo access by running the following: "
		echo "visudo"
		echo "This will open the /etc/sudoers file, which you will need to edit appropriately."
		echo "For more information, go to: https://wiki.archlinux.org/index.php/Sudo"
	fi

	read -p "This script will attempt to install the yaourt package manually. Are you sure you wish to proceed(y/n)?:  " -n 1 -r
	echo    
	if [[ $REPLY =~ ^[Yy]$ ]]
	then
	    choose_dir
	fi

echo
echo "Thanks for playing!"
}

function exit_funk {
	echo
        echo "Cleanup: "
        read -p "Do you wish to remove the build directories(y/n)?: " -n 1 -r
	echo
        if [[ $REPLY =~ ^[Yy]$ ]]
        then
        	cleanup
        fi

	echo
	echo "=================================================================================="
	echo "====================Thanks for using my script!==================================="
	echo "==You may use this script to upgrade by pointing it at an empty build directory.=="	
	echo "=================================================================================="
	echo
}

function cleanup {

	yaourt="yaourt"
	packageQuery="package-query"
	rm -rfv $installDir$yaourt $installDir$packageQuery
 
}

function check_distro {

	archcount=$(uname -a|grep ARCH|wc -l)
	if [ $archcount -lt 1 ]
	then
		echo "You must be running an Arch Distribution to run this script!"
		exit 0
	fi

}

check_distro
init
exit_funk

Offline

#2848 2016-12-30 06:51:37

Docbroke
Member
From: India
Registered: 2015-06-13
Posts: 1,438

Re: Post your handy self made command line utilities

why?

Offline

#2849 2016-12-30 06:57:20

eschwartz
Fellow
Registered: 2014-08-08
Posts: 4,097

Re: Post your handy self made command line utilities


Managing AUR repos The Right Way -- aurpublish (now a standalone tool)

Offline

#2850 2016-12-30 08:43:43

ugjka
Member
From: Latvia
Registered: 2014-04-01
Posts: 1,863
Website

Re: Post your handy self made command line utilities

I wrote a dumb-mp3-streamer for myself because I didn't want to set up an icecast server (too much work for what I needed )

You can do something like this with sox rec -t mp3 - | dumb-mp3-streamer and change recorder in pavucontrol to "Monitor". And boom you are streaming whatever is playin on your system.


https://ugjka.net
paru > yay | vesktop > discord
pacman -S spotify-launcher
mount /dev/disk/by-...

Offline

Board footer

Powered by FluxBB