# Pour les scripts : c'est ici

**URL:** <https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820>\
**Category:** Trucs et Astuces\
**Created:** [Février 20, 2016, 12:53 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820 "2016-02-20T12:53:11Z")\
**Posts on this page:** 14\
**Page:** 18

<div class="post-metadata">

**Author:** ![rsuinux](https://www.debian-fr.org/user_avatar/www.debian-fr.org/rsuinux/32/4554_2.png) [@rsuinux](https://www.debian-fr.org/u/rsuinux)\
**Post date:** [Février 21, 2016, 7:43 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820/342 "2016-02-21T19:43:26Z")

</div>

[quote=“agentsteel”]Pour ne pas enregistrer le son, il suffirait d’enlever la ligne

[mono]-f alsa -i hw:1[/mono]  
ainsi que l’option [mono]-ar “$myaudiorate”[/mono]

Par contre pour ce que tu veux faire, l’encodage ne sera peut-être pas optimal (le format lossless prend bcp de place disque).

Et pour de la vidéosurveillance il existe des softs plus adaptés : motion et zoneminder pour les plus connus[/quote]

je ne connaissais pas zoneminder. je vais regarder ce que c’est.

Merci.

---

<div class="post-metadata">

**Author:** ![agentsteel](https://www.debian-fr.org/letter_avatar_proxy/v4/letter/a/97f17d/32.png) [@agentsteel](https://www.debian-fr.org/u/agentsteel)\
**Post date:** [Février 21, 2016, 8:16 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820/343 "2016-02-21T20:16:44Z")

</div>

Un truc que je voulais faire depuis un moment : ouvrir une carte à l’emplacement ou une photo a été prise (coordonnées GPS)

dépendances : [mono]apt-get install jhead bc[/mono]

```auto
#!/bin/bash
#
# jpeg2map.sh
#
# script pour afficher le lieu correspondant aux coordonnées GPS d'une image JPEG, sur une carte
# (google maps/bing maps/yahoo maps/openstreetmap/...)
#
# AgentSteel pour debian-fr.org
# 30 Avril 2014
#
[[-z "$1"]] && { echo "Usage: $0 <fichier.jpg>"; exit 1;}
hash jhead >/dev/null 2>&1 || { echo "$0: Dépendance nécessaire non trouvée: jhead"; exit 1 ;}
hash bc >/dev/null 2>&1 || { echo "$0: Dépendance nécessaire non trouvée: bc"; exit 1 ;}

# séparateur : <LF>
IFS="
"
# recueillir les données GPS contenues dans l'entête EXIF du fichier JPEG
# le tout sera stocké dans un tableau (un élément = une ligne)
gpsdata=( $(jhead "$1" |grep "GPS") )
# si on a trouvé des données GPS
if [[-n "$gpsdata"]]; then
echo "Données EXIF brutes du fichier \"$1\" :"
echo "${gpsdata[@]}"
echo "--"

lat="${gpsdata[0]#*:}"; lon="${gpsdata[1]#*:}"

# tester si coord. GPS invalides
[["$lat" == " ? ?" || "$lon" == " ? ?"]] && { echo "$0: coordonnées GPS invalides!"; exit 1; }

# on sépare les valeurs (Nord/Sud, degré, minutes, secondes) pour la latitude
IFS=" " read -r -a latvalues <<< "$lat"
lat_NS="${latvalues[0]}"; lat_deg="${latvalues[1]%*d}"; lat_min="${latvalues[2]%*m}"; lat_sec="${latvalues[3]%*s}"
lat_sign=""; [["$lat_NS" == "S"]] && lat_sign="-"

# idem pour la longitude
IFS=" " read -r -a lonvalues <<< "$lon"
lon_EW="${lonvalues[0]}"; lon_deg="${lonvalues[1]%*d}"; lon_min="${lonvalues[2]%*m}"; lon_sec="${lonvalues[3]%*s}"
lon_sign=""; [["$lon_EW" == "W"]] && lon_sign="-"

# affichage du résultat après parsing
echo "Données EXIF fichier $1 (parsées) :"
echo "Latitude : $lat_NS $lat_deg°$lat_min'$lat_sec''"
echo "Longitude : $lon_EW $lon_deg°$lon_min'$lon_sec''"

# conversion Degrés, Minutes, Secondes en degrés décimaux
# latitude (degrés décimaux) = degrés + (minutes / 60) + (secondes / 3600)
# https://fr.wikipedia.org/wiki/Syst%C3%A8me_sexag%C3%A9simal#Conversion_de_minutes_et_secondes_en_fraction_d.C3.A9cimale_de_degr.C3.A9
lat_decimal="$(echo "$lat_deg + ( $lat_min / 60 ) + ( $lat_sec / 3600 )" | bc -l)"
lon_decimal="$(echo "$lon_deg + ( $lon_min / 60 ) + ( $lon_sec / 3600 )" | bc -l)"

# données finales
my_lat=$lat_sign$lat_decimal
my_lon=$lon_sign$lon_decimal

echo "--"
echo "Coordonnées en degrés décimaux : lat=$my_lat, lon=$my_lon"
echo "--"

echo "Liens à copier/coller dans votre navigateur pour voir le lieu sur une carte :"
echo

# niveau de zoom
zoom=15
zoom_mappy=10

# On commence par nos amis les Yankees
# https://support.google.com/maps/answer/18539?hl=en
# gmaps accepte la notation degrés,minutes,secondes
echo "(Google Maps) https://maps.google.com/?q=$lat_sign$lat_deg°$lat_min'$lat_sec\",$lon_sign$lon_deg°$lon_min'$lon_sec\"&t=h&z=$zoom"
echo
# http://msdn.microsoft.com/fr-fr/library/dn217138.aspx
echo "(Bing Maps) https://www.bing.com/maps/default.aspx?cp=$my_lat~$my_lon&lvl=$zoom&style=a&trfc=1"
echo
# https://help.yahoo.com/kb/maps/latitude-longitude-yahoo-maps-sln8927.html?impressions=true
# (pas de zoom dans l'url?)
echo "(Yahoo Maps) https://maps.yahoo.com/map/?lat=$my_lat&lon=$my_lon&t=h"
echo
# Mais les Russes nous observent aussi!
echo "(Yandex Maps) http://maps.yandex.com/?ll=$my_lon,$my_lat&l=sat,skl&z=$zoom"
echo
# Ha quand même on a aussi des trucs français
echo "(Geoportail) http://www.geoportail.gouv.fr/accueil?c=$my_lon,$my_lat&l=ORTHOIMAGERY.ORTHOPHOTOS::GEOPORTAIL:OGC:WMTS(1)&permalink=yes"
echo
echo "(Mappy.fr) http://fr.mappy.com/#/M2/Lp/TAppList/$my_lon,$my_lat/Z$zoom_mappy/"
echo
# http://wiki.openstreetmap.org/wiki/Export#Embeddable_HTML
echo "(OpenStreetMap) https://www.openstreetmap.org/#map=$zoom/$my_lat/$my_lon"

# Visu avec OpenLayers
# https://wiki.openstreetmap.org/wiki/OpenLayers_Marker
cat >"/tmp/tmp_openlayers_$$.html" <<EOF
<html><body>
  <div id="mapdiv"></div>
  <script src="http://www.openlayers.org/api/OpenLayers.js"></script>
  <script>
    map = new OpenLayers.Map("mapdiv");
    map.addLayer(new OpenLayers.Layer.OSM());
    var lonLat = new OpenLayers.LonLat( $my_lon, $my_lat )
          .transform(
            new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
            map.getProjectionObject() // to Spherical Mercator Projection
          );
    var zoom=$zoom;
    var markers = new OpenLayers.Layer.Markers( "Markers" );
    map.addLayer(markers);
    markers.addMarker(new OpenLayers.Marker(lonLat));
    map.setCenter (lonLat, zoom);
  </script>
</body></html>
EOF

# Visu avec leafletjs
# http://leafletjs.com/examples/quick-start.html
cat >"/tmp/tmp_leaflet_$$.html" <<EOF
<html>
<head>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />
</head>
<body>
<div id="map" style="width:640px; height:480px;"></div>
<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>
<script>
var map = L.map('map').setView([$my_lat, $my_lon], $zoom);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar'}).addTo(map);
</script>
</body>
</html>
EOF

# ouvrir dans le navigateur
x-www-browser "/tmp/tmp_openlayers_$$.html" "/tmp/tmp_leaflet_$$.html"

else
 echo "$0: le fichier \"$1\" ne contient pas de données EXIF GPS!"
fi

exit 0
```

---

<div class="post-metadata">

**Author:** ![M3t4linux](https://www.debian-fr.org/letter_avatar_proxy/v4/letter/m/5daacb/32.png) [@M3t4linux](https://www.debian-fr.org/u/M3t4linux)\
**Post date:** [Février 21, 2016, 8:27 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820/344 "2016-02-21T20:27:22Z")

</div>

Un petit script pour contrer les google glass

[http://julianoliver.com/output/category/log](http://julianoliver.com/output/category/log)

---

<div class="post-metadata">

**Author:** ![agentsteel](https://www.debian-fr.org/letter_avatar_proxy/v4/letter/a/97f17d/32.png) [@agentsteel](https://www.debian-fr.org/u/agentsteel)\
**Post date:** [Février 21, 2016, 8:27 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820/345 "2016-02-21T20:27:24Z")

</div>

ça pourrait s’adapter facilement pour les iMachins par exemple (ou tout autre appareil en wifi) ![:mrgreen:](https://www.debian-fr.org/uploads/default/original/1X/cc83e9b583138e48ff45f96609046b06d06c7f9d.gif "Mr. Green")

---

<div class="post-metadata">

**Author:** ![thuban](https://www.debian-fr.org/user_avatar/www.debian-fr.org/thuban/32/4177_2.png) [@thuban](https://www.debian-fr.org/u/thuban)\
**Post date:** [Février 21, 2016, 8:27 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820/346 "2016-02-21T20:27:26Z")

</div>

Intéressant ça… J’imagine bien des poches de résistance avec des raspberry pi installés ci et là. 🙂

---

<div class="post-metadata">

**Author:** ![rsuinux](https://www.debian-fr.org/user_avatar/www.debian-fr.org/rsuinux/32/4554_2.png) [@rsuinux](https://www.debian-fr.org/u/rsuinux)\
**Post date:** [Février 21, 2016, 8:27 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820/347 "2016-02-21T20:27:28Z")

</div>

j’ai regardé le script, mais si j’ai bien tout compris, il fait une recherche sur l’adresse mac des google glass.  
Mais si la plage des adresses mac changent, le script n’est plus valable, non?  
Je me goure-je?

---

<div class="post-metadata">

**Author:** ![agentsteel](https://www.debian-fr.org/letter_avatar_proxy/v4/letter/a/97f17d/32.png) [@agentsteel](https://www.debian-fr.org/u/agentsteel)\
**Post date:** [Février 21, 2016, 8:27 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820/348 "2016-02-21T20:27:29Z")

</div>

Oui, le principe est d’envoyer des trames à la borne wifi pour forcer la déconnexion d’un ensemble d’adresses MAC donné.

Sinon pour brouiller un signal gsm ça existe aussi («&nbsp;cellphone jammer&nbsp;») mais faut se renseigner un peu niveau légalité ![:116](https://www.debian-fr.org/uploads/default/original/1X/eae5ac515968d1af3d7141407139e6921afb85d3.gif "heu!")

---

<div class="post-metadata">

**Author:** ![vohu](https://www.debian-fr.org/user_avatar/www.debian-fr.org/vohu/32/4108_2.png) [@vohu](https://www.debian-fr.org/u/vohu)\
**Post date:** [Février 21, 2016, 8:46 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820/349 "2016-02-21T20:46:41Z")

</div>

Pour basculer facilement de langue sous XFCE.  
Ca pourrait être bien amélioré, mais ça me rend déjà bien service

```auto
#! /bin/bash

lg="$1"
lgMaj=`echo $lg | tr '[:lower:]' '[:upper:]'`
lgMin=`echo $lg | tr '[:upper:]' '[:lower:]'`
LANG=$lgMin'_'$lgMaj'.UTF-8'

res="`grep $LANG /etc/locale.gen | sed -e '/^[]*#/d' -e '/^$/d'`"
#echo $res

if [-z "$res"];
then
    echo "Installez les locales $LANG avec les UTF-8"
    echo "Attention pour FR : ne pas sélectionner un clavier sans touches mortes"
    echo "Appuyer sur Entrée pour continuer..."
    read a
    sudo apt-get update && apt-get install manpages-$lgMin locales -y -f
    sudo dpkg-reconfigure locales
    sudo locale-gen
    sudo dpkg-reconfigure keyboard-configuration
else
    echo "Changement de langue ($lgMin)..."

    export LANG=$LANG
    env | grep LANG

    xfce4-panel --quit
    LANG=$LANG xfce4-panel 2>/dev/null&
fi

```

---

<div class="post-metadata">

**Author:** ![xrxrxr](https://www.debian-fr.org/user_avatar/www.debian-fr.org/xrxrxr/32/5522_2.png) [@xrxrxr](https://www.debian-fr.org/u/xrxrxr)\
**Post date:** [Février 28, 2016, 7:31 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820/350 "2016-02-28T19:31:00Z")

</div>

bonjour moi j’ai fait script python pour afficher Linux logo faire un bleachbit mais je le modifie pour le laisser faire un bleachbit et qu’il s’éteigne

c’est mon premier script , Désoler s’il est degueux

[pastebin.com/raw/Q9TuBsdu](http://pastebin.com/raw/Q9TuBsdu)

#!/usr/bin/python

# -_- coding: latin-1 -_-

print(“Hello, Priviet , Nihao , Hola”)

print("this script will run linuxlogo & bleachbit cleaner and shutdown your computer, tested in DEBIAN , feel free to modify as you want ")

raw\_input(“Press Enter to continue…”)

print(“follow me on twitter i follow back @sincerebroth , and VK [vk.com/id215300685](http://vk.com/id215300685)”)

raw\_input(“Press Enter to continue…”)

import os  
os.system(“sudo apt-get install bleachbit”)

import os  
os.system(“sudo apt-get install linuxlogo”)

import os  
os.system(“linuxlogo”)

raw\_input(“Press Enter to continue…”)

import os  
os.system(“bleachbit --list”)

print("this is a list of all the bleachbit command that you can run to clean on your computer , you can customize my script here ")

raw\_input(“Press Enter to continue…”)

import os  
os.system(“bleachbit --clean apt.autoclean”)

import os  
os.system(“bleachbit --clean apt.autoremove”)

import os  
os.system(“bleachbit --clean apt.clean”)

import os  
os.system(“bleachbit --clean bash.history”)

import os  
os.system(“bleachbit --clean chromium.cache”)

import os  
os.system(“bleachbit --clean chromium.cookies”)

import os  
os.system(“bleachbit --clean chromium.current\_session”)

import os  
os.system(“bleachbit --clean chromium.dom”)

import os  
os.system(“bleachbit --clean chromium.form\_history”)

import os  
os.system(“bleachbit --clean chromium.history”)

import os  
os.system(“bleachbit --clean chromium.search\_engines”)

import os  
os.system(“bleachbit --clean chromium.vacuum”)

import os  
os.system(“bleachbit --clean deepscan.backup”)

import os  
os.system(“bleachbit --clean deepscan.ds\_store”)

import os  
os.system(“bleachbit --clean deepscan.thumbs\_db”)

import os  
os.system(“bleachbit --clean deepscan.tmp”)

import os  
os.system(“bleachbit --clean firefox.cache”)

import os  
os.system(“bleachbit --clean firefox.cookies”)

import os  
os.system(“bleachbit --clean firefox.crash\_reports”)

import os  
os.system(“bleachbit --clean firefox.dom”)

import os  
os.system(“bleachbit --clean firefox.download\_history”)

import os  
os.system(“bleachbit --clean firefox.forms”)

import os  
os.system(“bleachbit --clean firefox.passwords”)

import os  
os.system(“bleachbit --clean firefox.session\_restore”)

import os  
os.system(“bleachbit --clean firefox.site\_preferences”)

import os  
os.system(“bleachbit --clean firefox.url\_history”)

import os  
os.system(“bleachbit --clean firefox.vacuum”)

import os  
os.system(“bleachbit --clean flash.cache”)

import os  
os.system(“bleachbit --clean flash.cookies”)

import os  
os.system(“bleachbit --clean gimp.tmp”)

import os  
os.system(“bleachbit --clean gnome.run”)

import os  
os.system(“bleachbit --clean gnome.search\_history”)

import os  
os.system(“bleachbit --clean google\_chrome.cache”)

import os  
os.system(“bleachbit --clean google\_chrome.cookies”)

import os  
os.system(“bleachbit --clean google\_chrome.dom”)

import os  
os.system(“bleachbit --clean google\_chrome.form\_history”)

import os  
os.system(“bleachbit --clean google\_chrome.history”)

import os  
os.system(“bleachbit --clean google\_chrome.search\_engines”)

import os  
os.system(“bleachbit --clean google\_chrome.session”)

import os  
os.system(“bleachbit --clean google\_chrome.vacuum”)

import os  
os.system(“bleachbit --clean google\_earth.temporary\_files”)

import os  
os.system(“bleachbit --clean java.cache”)

import os  
os.system(“bleachbit --clean kde.cache”)

import os  
os.system(“bleachbit --clean kde.tmp”)

import os  
os.system(“bleachbit --clean konqueror.cookies”)

import os  
os.system(“bleachbit --clean konqueror.url\_history”)

import os  
os.system(“bleachbit --clean ‭opera.cache”)

import os  
os.system(“bleachbit --clean ‭opera.cookies”)

import os  
os.system(“bleachbit --clean opera.current\_session”)

import os  
os.system(“bleachbit --clean opera.dom”)

import os  
os.system(“bleachbit --clean opera.download\_history”)

import os  
os.system(“bleachbit --clean opera.search\_history”)

import os  
os.system(“bleachbit --clean opera.url\_history”)

import os  
os.system(“bleachbit --clean seamonkey.cache”)

import os  
os.system(“bleachbit --clean seamonkey.chat\_logs”)

import os  
os.system(“bleachbit --clean ‪seamonkey.cookies”)

import os  
os.system(“bleachbit --clean ‪seamonkey.download\_history”)

import os  
os.system(“bleachbit --clean seamonkey.history”)

import os  
os.system(“bleachbit --clean skype.chat\_logs”)

import os  
os.system(“bleachbit --clean system.cache”)

import os  
os.system(“bleachbit --clean system.clipboard”)

import os  
os.system(“bleachbit --clean system.localizations”)

import os  
os.system(“bleachbit --clean system.memory”)

import os  
os.system(“bleachbit --clean system.recent\_documents”)

import os  
os.system(“bleachbit --clean system.rotated\_logs”)

import os  
os.system(“bleachbit --clean system.tmp”)

import os  
os.system(“bleachbit --clean system.trash”)

import os  
os.system(“bleachbit --clean thumbnails.cache”)

import os  
os.system(“bleachbit --clean transmission.cache”)

print(“shutdown the computer”)

print(“shutdown system in 10 second”)  
print(“shutdown system in 9 second”)  
print(“shutdown system in 8 second”)  
print(“shutdown system in 7 second”)  
print(“shutdown system in 6 second”)  
print(“shutdown system in 5 second”)  
print(“shutdown system in 4 second”)  
print(“shutdown system in 3 second”)  
print(“shutdown system in 2 second”)  
print(“shutdown system in 1 second”)

import os  
os.system(“shutdown -h now”)

---

<div class="post-metadata">

**Author:** ![Arnaud](https://www.debian-fr.org/user_avatar/www.debian-fr.org/arnaud/32/4098_2.png) [@Arnaud](https://www.debian-fr.org/u/Arnaud)\
**Post date:** [Février 28, 2016, 7:31 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820/351 "2016-02-28T19:31:01Z")

</div>

Il est parfaitement inutile d’importer 1000 fois le module os, une seule fois suffit.  
De plus, il faudrait utiliser des balises code pour ton “script”.

---

<div class="post-metadata">

**Author:** ![seb-ksl](https://www.debian-fr.org/user_avatar/www.debian-fr.org/seb-ksl/32/2946_2.png) [@seb-ksl](https://www.debian-fr.org/u/seb-ksl)\
**Post date:** [Mars 7, 2016, 9:53 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820/352 "2016-03-07T09:53:00Z")

</div>

C’est effectivement assez moche. Plusieurs remarques :

- Pourquoi en Python plutôt qu’en Shell alors que tu passes ton temps à faire des appels à des commandes système ?
- Déjà signalé par Arnaud : pourquoi importer plusieurs fois le module `os` ?
- Formate ton bloc de code pour que ce soit plus facile à lire pour nous.
- Pour ceux qui ne savent pas ce qu’est bleachbit, tu peux peut-être détailler un peu le rôle de ton script.
- Tu exécutes des commandes avec sudo, tu supposes donc qu’il est installé et paramétré pour l’utilisateur courant. C’est loin d’être toujours le cas.
- D’ailleurs, ce serait bien que ton script prévienne de ce qu’il fait, surtout quand il lance des commandes avec les droits root.

---

<div class="post-metadata">

**Author:** ![seb-ksl](https://www.debian-fr.org/user_avatar/www.debian-fr.org/seb-ksl/32/2946_2.png) [@seb-ksl](https://www.debian-fr.org/u/seb-ksl)\
**Post date:** [Mai 31, 2016, 7:38 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820/353 "2016-05-31T19:38:56Z")

</div>

Ayant besoin de vérifier la stabilité de ma ligne ADSL, je me suis écrit un petit (~100 lignes) script Python pour faire un graphe du débit (download et upload) au cours du temps. Le script utilise en fait la sortie d’`ifstat` et l’injecte dans un graphe généré par `matplotlib`. Tout ça est déposé librement ici : [https://github.com/seb-ksl/ifstat\_plot](https://github.com/seb-ksl/ifstat_plot), et je copie ci-dessous.

À l’utilisation :

1. Installer les dépendances (`aptitude -R install ifstat python3 python3-matplotlib`).
2. Donner à la variable `INTERFACE` la valeur de l’interface réseau à surveiller.
3. Lancer `./ifstat_plot.py` pour commencer à mesurer le trafic.
4. Arrêter la mesure avec `Ctrl+c`
5. La sortie “brute” d’`ifstat` se trouve dans `ifstat.txt` et le graphe correspondant dans `ifstat.pdf`.

```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# ifstat_plot.py
#
# Copyright 2016 seb-ksl <seb@gelis.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
#
#

import subprocess
import sys
import logging
logging.basicConfig(level=logging.DEBUG, format="%(message)s")
logger = logging.getLogger("bandwidth_live_mon")
try:
    import matplotlib.pyplot as plt
except:
    logger.critical("Could not load matplotlib module for python3.")

INTERFACE = "eth0"

def start_ifstat():
    outf = open("ifstat.txt", "w")
    try:
        logger.debug("Running ifstat...")
        subprocess.call(["ifstat", "-ntb", "-i", INTERFACE], stdout=outf)
    except FileNotFoundError:
        logger.critical("Could not find ifstat.")
        sys.exit(1)
    except KeyboardInterrupt:
        logger.debug("Stopped ifstat.")
    finally:
        outf.close()

def graph():
    dates, rx, tx = [], [], []
    logger.debug("Parsing ifstat output.")
    with open("ifstat.txt", "r") as f:
        for l in f:
            if (not l.startswith(" ")) and (not l.startswith("H")):
                splitl = l.split()
                dates.append(splitl[0])
                rx.append(splitl[1])
                tx.append(splitl[2])

    ticks_spacing_dict = {(1800, 7199): ("00", "05", "10", "15", "20", "25",
                                         "30", "35", "40", "45", "50", "55"),
                          (7200, 17999): ("00", "15", "30", "45"),
                          (18000, 71999): ("00", "30"),
                          (72000, 1e8): ("00",)}

    ticks_spacing = ()
    for timespan in ticks_spacing_dict.keys():
        if timespan[0] < len(dates) < timespan[1]:
            ticks_spacing = ticks_spacing_dict[timespan]

    x_ticks, x_dates = [], []
    for (tick, date) in enumerate(dates):
        if len(ticks_spacing) > 0:
            if (date.split(":")[1] in ticks_spacing and
               date.split(":")[2] == "00"):
                x_ticks.append(tick)
                x_dates.append(date)
        else:
            if date.split(":")[2] == "00":
                x_ticks.append(tick)
                x_dates.append(date)

    logger.debug("Drawing figure.")
    fig = plt.figure(figsize=(10, 10))
    ax_rx = fig.add_subplot(211)
    ax_rx.set_xlabel("Time")
    ax_rx.set_xticks(x_ticks)
    ax_rx.set_xticklabels(x_dates, rotation=90)
    ax_rx.set_ylabel("RX in KB/s")

    try:
        ax_rx.plot(rx)
    except ValueError:
        logger.critical("Could not plot your stats properly. "
                        "Please check your interface ({}).".format(INTERFACE))
        sys.exit(1)

    ax_tx = fig.add_subplot(212)
    ax_tx.set_xlabel("Time")
    ax_tx.set_xticks(x_ticks)
    ax_tx.set_xticklabels(x_dates, rotation=90)
    ax_tx.set_ylabel("TX in KB/s")
    ax_tx.plot(tx)

    plt.tight_layout()
    logger.debug("Rendering figure.")
    plt.savefig("ifstat.pdf")
    logger.info("Figure saved to ifstat.pdf")

def main():
    start_ifstat()
    graph()

if __name__ == ' __main__':
    main()

```

C’est largement perfectible, mais en l’état ça fait le job 🙂. Je prends toutes les remarques et suggestions !

---

<div class="post-metadata">

**Author:** ![lsam](https://www.debian-fr.org/user_avatar/www.debian-fr.org/lsam/32/12965_2.png) [@lsam](https://www.debian-fr.org/u/lsam)\
**Post date:** [Juin 1, 2016, 12:21 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820/354 "2016-06-01T12:21:57Z")

</div>

Bonjour,

J’ai essayé ton script ifstat\_plot.py par curiosité. Pour _matplotlib_ ne pas oublier d’installer _python3-tk_.

Sinon j’obtiens cette erreur :  
` subprocess.run([“ifstat”, “-ntb”, “-i”, INTERFACE], stdout=outf)
AttributeError: ‘module’ object has no attribute ‘run’`

---

<div class="post-metadata">

**Author:** ![seb-ksl](https://www.debian-fr.org/user_avatar/www.debian-fr.org/seb-ksl/32/2946_2.png) [@seb-ksl](https://www.debian-fr.org/u/seb-ksl)\
**Post date:** [Juin 1, 2016, 2:32 UTC](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820/355 "2016-06-01T14:32:28Z")

</div>

Salut !

Et merci pour le retour 🙂.  
Pour `python3-tk`, ce n’est que recommandé par `apt` et je pense que pour ce script ça fonctionnera sans. En vrai j’ai ça comme jeu de dépendances pour `python3-matplotlib` :

```auto
Dépend: python3-dateutil, python-matplotlib-data (>= 1.5.1-1), python3-pyparsing (>= 1.5.6),
        python3-six (>= 1.4), python3-tz, libjs-jquery, libjs-jquery-ui, python3-numpy (>=
        1:1.10.0~b1), python3-numpy-abi9, python3 (< 3.6), python3 (>= 3.5~), python3-cycler, libc6
        (>= 2.14), libfreetype6 (>= 2.2.1), libgcc1 (>= 1:3.0), libpng16-16 (>= 1.6.2-1), libstdc++6
        (>= 5.2), libtcl8.6 (>= 8.6.0), libtk8.6 (>= 8.6.0)
Recommande: python3-pil, python3-tk
Suggère: dvipng, ffmpeg, gir1.2-gtk-3.0, ghostscript, inkscape, ipython3, librsvg2-common,
         python-matplotlib-doc, python3-cairocffi, python3-gi, python3-gi-cairo, python3-gobject,
         python3-nose, python3-pyqt4, python3-scipy, python3-sip, python3-tornado,
         texlive-extra-utils, texlive-latex-extra, ttf-staypuft

```

Et comme je prends soin d’utiliser le flag `-R` d’`aptitude` pour ne pas installer les recommandations, … 😉

Le second problème est que la méthode `.run()` de `subprocess` n’est apparue qu’avec la version 3.5 de Python. Si tu tournes sur la version 3.4, essaie simplement de remplacer ce `.run()` par `.call`, ça devrait fonctionner 🙂.

Édit : j’ai mis à jour le code sur ce fil et sur Github, j’utilise `.call()` au lieu de `.run()`, étant donné que la branche stable de notre distribution préférée fournit la version 3.4 de Python.

[Page précédente](https://www.debian-fr.org/t/pour-les-scripts-cest-ici/3820.md?page=17)
