Affichage des articles dont le libellé est python. Afficher tous les articles
Affichage des articles dont le libellé est python. Afficher tous les articles

mercredi 4 avril 2012

ipython, IDE web, scipy

sudo apt-get install ipython

Lancement de l'interface
ipython notebook --pylab

Installer le logiciel pour le calcul mathématique et scientifique sous python
sudo apt-get install python-scipy

Installation du module pylab
sudo apt-get install python-matplotlib


code source

from scipy import *
from scipy.special import jn, jn_zeros
def drumhead_height(n, k, distance, angle, t):
nth_zero = jn_zeros(n, k)
return cos(t)*cos(n*angle)*jn(n, distance*nth_zero)
theta = r_[0:2*pi:50j]
radius = r_[0:1:50j]
x = array([r*cos(theta) for r in radius])
y = array([r*sin(theta) for r in radius])
z = array([drumhead_height(1, 1, r, theta, 0.5) for r in radius]) import pylab
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
fig = pylab.figure()
ax = Axes3D(fig)
ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.jet)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
pylab.show()

Sources
http://ipython.org/ipython-doc/stable/interactive/htmlnotebook.html
http://docs.scipy.org/doc/scipy/reference/tutorial/special.html
http://docs.scipy.org/doc/

pyhon, module

cd /var/www/html
[root@test11 html]# ls

info.php

[root@test11 html]# touch index.html
[root@test11 html]# view index.html

(make your Welcome text message)

[root@test11 html]# python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
localhost - - [04/Apr/2012 11:05:26] "GET / HTTP/1.1" 200 -
localhost - - [04/Apr/2012 11:05:26] code 404, message File not found
localhost - - [04/Apr/2012 11:05:26] "GET /favicon.ico HTTP/1.1" 404



L'option m permet de définir les modules utilisés
-m module-name
Searches sys.path for the named module and runs the correspond‐
ing .py file as a script.


Liste des modules
  • In ipython you can type "importTab".

  • In the standard Python interpreter, you can type "help('modules')".

  • At the command-line, you can use pydoc modules.

  • In a script, call pkgutil.iter_modules().


lancer ipython
In [2]: import
Display all 573 possibilities? (y or n)
ANSI formatter
AptUrl fpectl
ArgImagePlugin fpformat
BaseHTTPServer fractions
Bastion ftplib
BdfFontFile functools
BmpImagePlugin future_builtins
BufrStubImagePlugin gc
CDROM gconf
CGIHTTPServer gdbm
Canvas genericpath
CommandNotFound getopt
ConfigParser getpass
ContainerIO gettext
Cookie gi
Crypto gio
CurImagePlugin glib
DLFCN glob
DcxImagePlugin gnome_sudoku
Dialog gnomekeyring
DistUpgrade gobject
DocXMLRPCServer google
EpsImagePlugin grp
ExifTags gst
FSM gstoption
FileDialog gtk
FitsStubImagePlugin gtkunixprint
FixTk gwibber
FliImagePlugin gzip
FontFile hashlib
FpxImagePlugin heapq
GbrImagePlugin hmac
GdImageFile hotshot
GifImagePlugin hpmudext
GimpGradientFile htmlentitydefs
GimpPaletteFile htmllib
GnuPGInterface httplib
GribStubImagePlugin httplib2
HTMLParser ibus
Hdf5StubImagePlugin ihooks
IN imageop
IPython imaplib
IcnsImagePlugin imghdr
IcoImagePlugin imp
ImImagePlugin importlib
Image imputil
ImageChops inspect
ImageCms io
ImageColor itertools
ImageDraw jockey
ImageDraw2 json
ImageEnhance keyring
ImageFile keyword
ImageFileIO language_support_pkgs
ImageFilter launchpadlib
ImageFont lazr
ImageGL lib2to3
ImageGrab libproxy
ImageMath libxml2
ImageMode libxml2mod
ImageOps linecache
ImagePalette linuxaudiodev
ImagePath locale
ImageQt logging
ImageSequence louis
ImageShow lsb_release
ImageStat macpath
ImageTransform macurl2path
ImageWin mailbox
ImtImagePlugin mailcap
IptcImagePlugin mako
JpegImagePlugin markupbase
LanguageSelector markupsafe
McIdasImagePlugin marshal
MicImagePlugin math
MimeWriter md5
MpegImagePlugin mhlib
MspImagePlugin mimetools
NvidiaDetector mimetypes
OleFileIO mimify
Onboard miniterm
OpenSSL mmap
PAMmodule modulefinder
PIL multifile
PSDraw multiprocessing
PaletteFile mutex
PalmImagePlugin mx
PcdImagePlugin netrc
PcfFontFile new
PcxImagePlugin nis
PdfImagePlugin nntplib
PixarImagePlugin ntpath
PngImagePlugin nturl2path
PpmImagePlugin numbers
PsdImagePlugin oauth
PyQt4 oneconf
Queue opcode
Quirks operator
ScrolledText optparse
SgiImagePlugin orca
SimpleDialog os
SimpleHTTPServer os2emxpath
SimpleXMLRPCServer ossaudiodev
SocketServer packagekit
SpiderImagePlugin pango
StringIO pangocairo
SunImagePlugin papyon
TYPES parallelmagic
TarIO parser
TgaImagePlugin pcardext
TiffImagePlugin pdb
TiffTags pexpect
Tix pickle
Tkconstants pickletools
Tkdnd pilconvert
Tkinter pildriver
UbuntuSystemService pilfile
UpdateManager pilfont
UserDict pilprint
UserList pipes
UserString piston_mini_client
WalImageFile pkg_resources
WmfImagePlugin pkgutil
XKit platform
XVThumbImagePlugin plistlib
XbmImagePlugin popen2
XpmImagePlugin poplib
_LWPCookieJar posix
_MozillaCookieJar posixfile
__builtin__ posixpath
__future__ pprint
__main__ problem_report
__phello__ profile
_abcoll pstats
_ast pty
_bisect pwd
_bsddb pxssh
_codecs pyHnj
_codecs_cn py_compile
_codecs_hk pyatspi
_codecs_iso2022 pychecker
_codecs_jp pychecker2
_codecs_kr pyclbr
_codecs_tw pycurl
_collections pydoc
_csv pydoc_data
_ctypes pyexpat
_ctypes_test pygst
_curses pygtk
_curses_panel pyinotify
_dbus_bindings pynotify
_dbus_glib_bindings quopri
_elementtree random
_functools re
_hashlib readline
_heapq reportlab
_hotshot repr
_imaging resource
_imagingcms rexec
_imagingft rfc822
_imagingmath rlcompleter
_io robotparser
_json runpy
_locale scanext
_lsprof sched
_multibytecodec screen
_multiprocessing select
_pyio serial
_random sessioninstaller
_renderPM sets
_rl_accel sgmllib
_socket sgmlop
_sqlite3 sha
_sre shelve
_ssl shlex
_strptime shutil
_struct signal
_symtable simplegeneric
_testcapi simplejson
_threading_local sip
_warnings sipconfig
_weakref sipconfig_nd
_weakrefset site
abc sitecustomize
aifc smbc
antigravity smtpd
anydbm smtplib
appindicator sndhdr
apport socket
apport_python_hook softwarecenter_aptd_plugins
apt softwareproperties
apt_inst speechd
apt_pkg speechd_config
aptdaemon spwd
aptsources sqlite3
argparse sre
array sre_compile
ast sre_constants
asynchat sre_parse
asyncore ssl
atexit stat
atk statvfs
audiodev storemagic
audioop string
autoreload stringold
axi stringprep
base64 strop
bdb struct
binascii subprocess
binhex sunau
bisect sunaudio
brlapi symbol
bsddb sympyprinting
butterfly symtable
bz2 sys
cPickle sysconfig
cProfile syslog
cStringIO tabnanny
cairo tarfile
calendar telepathy
cgi telnetlib
cgitb tempfile
chardet termios
checkbox test
checkbox_qt textwrap
chunk this
cmath thread
cmd threading
code time
codecs timeit
codeop tkColorChooser
collections tkCommonDialog
colorsys tkFileDialog
commands tkFont
compileall tkMessageBox
compiler tkSimpleDialog
computerjanitor toaiff
configglue token
configobj tokenize
contextlib trace
cookielib traceback
copy ttk
copy_reg tty
crypt turtle
csv twisted
ctypes types
cups ubuntu_sso
cupsext ubuntuone
cupshelpers ufw
curl unicodedata
curses unittest
datetime uno
dateutil unohelper
dbhash urllib
dbm urllib2
dbus urlparse
deb822 usbcreator
debconf user
debian uu
debian_bundle uuid
debtagshw validate
decimal virtkey
decorator vtemodule
defer wadllib
difflib warnings
dircache wave
dirspec weakref
dis webbrowser
distutils whichdb
dl wsgiref
doctest wx
drv_libxml2 wxPython
dsextras wxversion
dumbdbm xapian
dummy_thread xdg
dummy_threading xdiagnose
duplicity xdrlib
email xml
encodings xmllib
errno xmlrpclib
exceptions xxsubtype
farsight zeitgeist
fcntl zipfile
fdpexpect zipimport
filecmp zlib
fileinput zope
fnmatch



lundi 19 mars 2012

La création d'un miroir pour les paquets va vous permettre de créer et de maintenir la copie conforme de dépôts (officiels ou non) en local. Ce n'est donc pas une procédure à prendre à la légère, car vous allez aspirer complètement le contenu d'un ou plusieurs dépôts et les stocker dans un répertoire.
Installation de « apt-mirror »
C'est très simple : il suffit d'installer le paquet « apt-mirror. ».

apt-get install apt-mirror

Préparation de votre sauvegarde
Dans mon exemple, je vais configurer un disque dur externe. Mais un autre emplacement est possible tant que vous en connaissez le chemin complet. Cela peut donc être un simple répertoire dans votre compte utilisateur.
Le cas du disque externe est celui que j'utilise. Mon disque dur se balade de mon boulot où j'ai un gros accès internet, à mon chez moi où la connexion est plus modeste et jusqu'à mes parents (sans internet) ou mes amis.
Mon disque dur est automatiquement monté sous « /media/DDPortable ». Nous allons donc créer un répertoire nommé « miroir » qui contiendra le miroir complet :
mkdir /media/DDPortable/miroir
Dans celui-ci, nous avons besoin de créer 3 sous-répertoires afin que apt-mirror puisse fonctionner :
mkdir /media/DDPortable/miroir/mirror
mkdir /media/DDPortable/miroir/skel
mkdir /media/DDPortable/miroir/var
Ces répertoires peuvent être tout aussi bien créés en utilisant Nautilus et sa possibilité de créer des dossiers
Pour les puristes :
mkdir -p /media/DDPortable/miroir/{mirror,skel,var}
Configuration de « apt-mirror »
Par défaut, apt-mirror utilise son propre fichier de configuration : /etc/apt/mirror.list.
############# config ##################
#
set base_path /media/data/miroir
#
set mirror_path $base_path/mirror
set skel_path $base_path/skel
set var_path $base_path/var
set cleanscript $var_path/clean.sh
set defaultarch i386
# set postmirror_script $var_path/postmirror.sh
# set run_postmirror 0
set nthreads 20
set _tilde 0
#
############# end config ##############
deb http://ftp.free.fr/mirrors/ftp.ubuntu.com/ubuntu/ lucid main restricted
deb http://ftp.free.fr/mirrors/ftp.ubuntu.com/ubuntu/ lucid-security main $
deb http://ftp.free.fr/mirrors/ftp.ubuntu.com/ubuntu/ lucid-updates main r$


deb http://ftp.free.fr/mirrors/ftp.ubuntu.com/ubuntu/ lucid universe multi$
deb http://ftp.free.fr/mirrors/ftp.ubuntu.com/ubuntu/ lucid-security unive$
deb http://ftp.free.fr/mirrors/ftp.ubuntu.com/ubuntu/ lucid-updates univer$

#deb http://archive.ubuntu.com/ubuntu natty main restricted universe multi$
#deb http://archive.ubuntu.com/ubuntu natty-security main restricted unive$
#deb http://archive.ubuntu.com/ubuntu natty-updates main restricted univer$
#deb http://archive.ubuntu.com/ubuntu natty-proposed main restricted unive$
#deb http://archive.ubuntu.com/ubuntu natty-backports main restricted univ$

#deb-src http://archive.ubuntu.com/ubuntu natty main restricted universe m$
#deb-src http://archive.ubuntu.com/ubuntu natty-security main restricted u$
#deb-src http://archive.ubuntu.com/ubuntu natty-updates main restricted un$
#deb-src http://archive.ubuntu.com/ubuntu natty-proposed main restricted u$
#deb-src http://archive.ubuntu.com/ubuntu natty-backports main restricted $

clean http://archive.ubuntu.com/ubuntu
script de post install
Il ne faut pas oublier de donner les droits pour les scripts de post-installation sinon impossible de relancer apt-mirror.
sudo chmod +x /var/spool/apt-mirror/var/postmirror.sh
sudo chmod +x /var/spool/apt-mirror/var/clean.sh
bug eventuel
si jamais apt-mirror refuse de se relancer; c'est qu'un fichier le vérouille. Il faut supprimer

rm -f /media/DDPortable/mirror/var/apt-mirror.lock



Mise en place du serveur web
Déplacer vous dans le répertoire contenant le dossier que vous voulez partager en HTTP et taper la commande suivante.
python -m SimpleHTTPServer 80 &
sources
http://doc.ubuntu-fr.org/tutoriel/creer_un_miroir_de_depot_local
http://doc.ubuntu-fr.org/depots_lucid

samedi 7 janvier 2012

py processing

http://code.google.com/p/pyprocessing/ importer des fonctions processing sous python .


à tester

jeudi 29 décembre 2011

python -> G20

Python déjà installlé.

hello.py
print "Hello world !"

debarm:~# python hello.py
Hello world !

mardi 17 mai 2011

fortuneteller python

#!/usr/bin/env python

"""PyQt4 port of the network/fortuneserver example from Qt v4.x"""

import random

from PyQt4 import QtCore, QtGui, QtNetwork


class Server(QtGui.QDialog):
def __init__(self, parent=None):
super(Server, self).__init__(parent)

statusLabel = QtGui.QLabel()
quitButton = QtGui.QPushButton("Quit")
quitButton.setAutoDefault(False)

self.tcpServer = QtNetwork.QTcpServer(self)
if not self.tcpServer.listen():
QtGui.QMessageBox.critical(self, "Fortune Server",
"Unable to start the server: %s." % self.tcpServer.errorString())
self.close()
return

statusLabel.setText("The server is running on port %d.\nRun the "
"Fortune Client example now." % self.tcpServer.serverPort())

self.fortunes = (
"You've been leading a dog's life. Stay off the furniture.",
"You've got to think about tomorrow.",
"You will be surprised by a loud noise.",
"You will feel hungry again in another hour.",
"You might have mail.",
"You cannot kill time without injuring eternity.",
"Computers are not intelligent. They only think they are.")

quitButton.clicked.connect(self.close)
self.tcpServer.newConnection.connect(self.sendFortune)

buttonLayout = QtGui.QHBoxLayout()
buttonLayout.addStretch(1)
buttonLayout.addWidget(quitButton)
buttonLayout.addStretch(1)

mainLayout = QtGui.QVBoxLayout()
mainLayout.addWidget(statusLabel)
mainLayout.addLayout(buttonLayout)
self.setLayout(mainLayout)

self.setWindowTitle("Fortune Server")

def sendFortune(self):
block = QtCore.QByteArray()
out = QtCore.QDataStream(block, QtCore.QIODevice.WriteOnly)
out.setVersion(QtCore.QDataStream.Qt_4_0)
out.writeUInt16(0)
fortune = self.fortunes[random.randint(0, len(self.fortunes) - 1)]

try:
# Python v3.
fortune = bytes(fortune, encoding='ascii')
except:
# Python v2.
pass

out.writeString(fortune)
out.device().seek(0)
out.writeUInt16(block.size() - 2)

clientConnection = self.tcpServer.nextPendingConnection()
clientConnection.disconnected.connect(clientConnection.deleteLater)

clientConnection.write(block)
clientConnection.disconnectFromHost()


if __name__ == '__main__':

import sys

app = QtGui.QApplication(sys.argv)
server = Server()
random.seed(None)
sys.exit(server.exec_())



#!/usr/bin/env python

"""PyQt4 port of the network/fortuneclient example from Qt v4.x"""

from PyQt4 import QtCore, QtGui, QtNetwork


class Client(QtGui.QDialog):
def __init__(self, parent=None):
super(Client, self).__init__(parent)

self.blockSize = 0
self.currentFortune = ''

hostLabel = QtGui.QLabel("&Server name:")
portLabel = QtGui.QLabel("S&erver port:")

self.hostLineEdit = QtGui.QLineEdit('Localhost')
self.portLineEdit = QtGui.QLineEdit()
self.portLineEdit.setValidator(QtGui.QIntValidator(1, 65535, self))

hostLabel.setBuddy(self.hostLineEdit)
portLabel.setBuddy(self.portLineEdit)

self.statusLabel = QtGui.QLabel("This examples requires that you run "
"the Fortune Server example as well.")

self.getFortuneButton = QtGui.QPushButton("Get Fortune")
self.getFortuneButton.setDefault(True)
self.getFortuneButton.setEnabled(False)

quitButton = QtGui.QPushButton("Quit")

buttonBox = QtGui.QDialogButtonBox()
buttonBox.addButton(self.getFortuneButton,
QtGui.QDialogButtonBox.ActionRole)
buttonBox.addButton(quitButton, QtGui.QDialogButtonBox.RejectRole)

self.tcpSocket = QtNetwork.QTcpSocket(self)

self.hostLineEdit.textChanged.connect(self.enableGetFortuneButton)
self.portLineEdit.textChanged.connect(self.enableGetFortuneButton)
self.getFortuneButton.clicked.connect(self.requestNewFortune)
quitButton.clicked.connect(self.close)
self.tcpSocket.readyRead.connect(self.readFortune)
self.tcpSocket.error.connect(self.displayError)

mainLayout = QtGui.QGridLayout()
mainLayout.addWidget(hostLabel, 0, 0)
mainLayout.addWidget(self.hostLineEdit, 0, 1)
mainLayout.addWidget(portLabel, 1, 0)
mainLayout.addWidget(self.portLineEdit, 1, 1)
mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2)
mainLayout.addWidget(buttonBox, 3, 0, 1, 2)
self.setLayout(mainLayout)

self.setWindowTitle("Fortune Client")
self.portLineEdit.setFocus()

def requestNewFortune(self):
self.getFortuneButton.setEnabled(False)
self.blockSize = 0
self.tcpSocket.abort()
self.tcpSocket.connectToHost(self.hostLineEdit.text(),
int(self.portLineEdit.text()))

def readFortune(self):
instr = QtCore.QDataStream(self.tcpSocket)
instr.setVersion(QtCore.QDataStream.Qt_4_0)

if self.blockSize == 0:
if self.tcpSocket.bytesAvailable() < 2:
return

self.blockSize = instr.readUInt16()

if self.tcpSocket.bytesAvailable() < self.blockSize:
return

nextFortune = instr.readString()

try:
# Python v3.
nextFortune = str(nextFortune, encoding='ascii')
except TypeError:
# Python v2.
pass

if nextFortune == self.currentFortune:
QtCore.QTimer.singleShot(0, self.requestNewFortune)
return

self.currentFortune = nextFortune
self.statusLabel.setText(self.currentFortune)
self.getFortuneButton.setEnabled(True)

def displayError(self, socketError):
if socketError == QtNetwork.QAbstractSocket.RemoteHostClosedError:
pass
elif socketError == QtNetwork.QAbstractSocket.HostNotFoundError:
QtGui.QMessageBox.information(self, "Fortune Client",
"The host was not found. Please check the host name and "
"port settings.")
elif socketError == QtNetwork.QAbstractSocket.ConnectionRefusedError:
QtGui.QMessageBox.information(self, "Fortune Client",
"The connection was refused by the peer. Make sure the "
"fortune server is running, and check that the host name "
"and port settings are correct.")
else:
QtGui.QMessageBox.information(self, "Fortune Client",
"The following error occurred: %s." % self.tcpSocket.errorString())

self.getFortuneButton.setEnabled(True)

def enableGetFortuneButton(self):
self.getFortuneButton.setEnabled(bool(self.hostLineEdit.text() and
self.portLineEdit.text()))


if __name__ == '__main__':

import sys

app = QtGui.QApplication(sys.argv)
client = Client()
client.show()
sys.exit(client.exec_())

PYQT

Install and run "hello world" example
  • apt-cache search pyqt
  • sudo apt-get install python-qt4
  • Create a file ~/tmp/helloworld.py
    import sys
    from PyQt4.QtGui import *
    app = QApplication(sys.argv)
    button = QPushButton("Hello World", None)
    button.show()
    app.exec_()
  • Run it:
    python ~/tmp/helloworld.py
    You should see a window with a single button pop up.

Install additional examples
  • For more examples, install the python-qt4-doc package:
    sudo apt-get install python-qt4-doc
  • After installation, the examples are located at:
    /usr/share/doc/python-qt4-doc/examples