Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts
Wednesday, October 11, 2017
Saturday, September 30, 2017
Saturday, October 24, 2015
Running multiple python apps with nginx and uwsgi in emperor mode
Quote from site
(...)This is a recipe on how to easily run multiple Python web applications using uwsgi server (in emperor mode) and behind nginx. Most existing docs and blogs would show how to manually start uwsgi to run a single app. In this post, I'll show how to configure uwsgi as a system service (with upstart) capable of serving multiple python WSGI compliant web applications by simply placing them in a standard location and adding an standard xml file.(...)
Wednesday, October 14, 2015
Turn a function in asynchrounous mode
https://pykodz.wordpress.com/2010/11/15/async-decorator/
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from threading import Thread
from time import sleep
class async(Thread):
def __init__(self, callback, errback):
super(async, self).__init__()
self.callback = callback
self.errback = errback
def __call__(self, func):
# à l'appel de la fonction, on récupère juste la fonction
# et ses arguments, et on lance notre thread
def wrapper(*args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
self.start()
return wrapper
def run(self):
try:
retval = self.func(*self.args, **self.kwargs)
self.callback(retval)
except Exception as err:
self.errback(err)
def my_callback(retval):
print "CALLBACK:", retval
# ici on peut faire des opérations supplémentaires
# sur la valeur renvoyée par la fonction.
# ce code est appelé par le thread, il ne peut donc
# pas bloquer notre thread principal
def my_errback(err):
print "ERRBACK", err
# ici on peut re-lancer l'exception, ou simplement
# l'ignorer. Ce code est également appelé dans le thread
@async(my_callback, my_errback)
def ma_fonction_reussie(n):
sleep(n)
return n
@async(my_callback, my_errback)
def ma_fonction_foireuse(n):
sleep(n)
raise AttributeError("Got %s, expected 'foo'" % n)
ma_fonction_reussie(5)
ma_fonction_foireuse(7)
# histoire de passer le temps pendant ce temps là...
for i in range(10):
print "MAIN:", i
sleep(1)
Remote command with Paramiko-Expect
https://www.snip2code.com/Snippet/430662/Python-3-x-SSH-with-Paramiko---Paramiko-
#!/usr/bin/env python
# PyNet Class Exercises by Nick Ellson
__author__ = "Nick Ellson"
import paramiko
from paramikoe import SSHClientInteraction
import getpass
# Collect an target, user, and password. This example assumes that privilege level 15 is on your Cisco VTY.
ip = input("Enter Host: ")
username = input("Enter Username: ")
password = getpass.getpass()
#Initialize teh Paramiko connection
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote_conn_pre.connect(ip, username=username, password=password, allow_agent=False, look_for_keys=False)
print ("SSH connection established to %s" % ip)
# Here we make a simple Paramiko only shell because we do not yet have a prompt example to work with for Expect.
# So this will basically log us in, and grab that prompt that we land with, and disconnect.
remote_conn = remote_conn_pre.invoke_shell()
output = remote_conn.recv(1000).decode("utf-8")
prompt = output.strip()
remote_conn.close()
# Now we reconnect with the paramiko expect module and we have a nice interactive conversation.
remote_conn_pre.connect(ip, username=username, password=password, allow_agent=False, look_for_keys=False)
interact = SSHClientInteraction(remote_conn_pre, timeout=20, display=False)
#Logged in, wait for the prompt to display.
interact.expect(prompt)
#Shut off the --more-- prompting
interact.send('terminal length 0')
interact.expect(prompt)
#We don't care about the output for that last command, so just clear the buffer.
cmd_output = interact.current_output_clean
#Let's grab something BIG that use dto be a real timing issue the old way, not knowing how long it might take to get a full
# running config over a WAN link. Now we do not care, we will simply wait to the prompt shows up.
interact.send('show running-config')
interact.expect(prompt)
cmd_output = interact.current_output_clean
print (cmd_output)
#Close our session
remote_conn_pre.close()
Monday, October 12, 2015
Spnner - AsyncIO example-
Nice example using asyncio in Python3.5
# spinner_await.py
# credits: Example by Luciano Ramalho inspired by
# Michele Simionato's multiprocessing example in the python-list:
# https://mail.python.org/pipermail/python-list/2009-February/538048.html
# BEGIN SPINNER_AWAIT
import asyncio
import itertools
import sys
async def spin(msg): # <1>
write, flush = sys.stdout.write, sys.stdout.flush
for char in itertools.cycle('|/-\\'):
status = char + ' ' + msg
write(status)
flush()
write('\x08' * len(status))
try:
await asyncio.sleep(.1) # <3>
except asyncio.CancelledError: # <4>
break
write(' ' * len(status) + '\x08' * len(status))
async def slow_function(): # <5>
# pretend waiting a long time for I/O
#await asyncio.sleep(3) # <6>
for i in range(100000000):
i += 1
await asyncio.sleep(.0000001)
return 42
async def supervisor(): # <7>
spinner = asyncio.ensure_future(spin('thinking!')) # <8>
print('spinner object:', spinner) # <9>
result = await slow_function() # <10>
spinner.cancel() # <11>
return result
def main():
loop = asyncio.get_event_loop() # <12>
result = loop.run_until_complete(supervisor()) # <13>
loop.close()
print('Answer:', result)
if __name__ == '__main__':
Friday, September 25, 2015
Reading large GZIP files with Python
Thanks to
Spencer Rathbun
Here Sepencer's way to read, large files with Python, amazingly I have adopted nearly, the same strategy for one of my scripts at work...thanks to Dave Beazley for its fantastic job on genrators in Python
Spencer Rathbun
Here Sepencer's way to read, large files with Python, amazingly I have adopted nearly, the same strategy for one of my scripts at work...thanks to Dave Beazley for its fantastic job on genrators in Python
#!/usr/bin/env python
import gzip, bz2
import os
import fnmatch
def gen_find(filepat,top):
for path, dirlist, filelist in os.walk(top):
for name in fnmatch.filter(filelist,filepat):
yield os.path.join(path,name)
def gen_open(filenames):
for name in filenames:
if name.endswith(".gz"):
yield gzip.open(name)
elif name.endswith(".bz2"):
yield bz2.BZ2File(name)
else:
yield open(name)
def gen_cat(sources):
for s in sources:
for item in s:
yield item
def main(regex, searchDir):
fileNames = gen_find(regex,searchDir)
fileHandles = gen_open(fileNames)
fileLines = gen_cat(fileHandles)
for line in fileLines:
print line
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Search globbed files line by line', version='%(prog)s 1.0')
parser.add_argument('regex', type=str, default='*', help='Regular expression')
parser.add_argument('searchDir', , type=str, default='.', help='list of input files')
args = parser.parse_args()
main(args.regex, args.searchDir)
Saturday, May 16, 2015
La puissance cachée des coroutines
Voilà un excellent article sur le sujet et en Français :
http://zestedesavoir.com/articles/232/la-puissance-cachee-des-coroutines/
http://zestedesavoir.com/articles/232/la-puissance-cachee-des-coroutines/
Thursday, March 12, 2015
Roll your own server in 50 lines of code
This article explains how to dispatch requests to python modules.
Where nice way to organize code.
https://muharem.wordpress.com/2007/05/29/roll-your-own-server-in-50-lines-of-code/
Where nice way to organize code.
https://muharem.wordpress.com/2007/05/29/roll-your-own-server-in-50-lines-of-code/
Catch “before/after function call” events for all functions in class
Monday, January 19, 2015
Recursive Functional State Machine
https://code.activestate.com/recipes/577709-recursive-functional-state-machine/?in=lang-python
Here is a pure Python FSM
https://github.com/oxplot/fysom/blob/master/fysom.py
Here is a pure Python FSM
https://github.com/oxplot/fysom/blob/master/fysom.py
Sending Email From A Python Program (Python recipe)
Saturday, November 8, 2014
A practical introduction to functional programming
Mary Rose expose some functional programming concepts with Python.
http://maryrosecook.com/blog/post/a-practical-introduction-to-functional-programming
http://maryrosecook.com/blog/post/a-practical-introduction-to-functional-programming
Tuesday, July 29, 2014
Easy Web Scraping with Python
Nice article from the author of 'Flask Mega Tutotial"
http://blog.miguelgrinberg.com/post/easy-web-scraping-with-python
http://blog.miguelgrinberg.com/post/easy-web-scraping-with-python
Saturday, July 12, 2014
Running multiplie Python apps with uwsgi and nginx
Quote from site :
This is a recipe on how to easily run multiple Python web applications using uwsgi server (in emperor mode) and behind nginx. Most existing docs and blogs would show how to manually start uwsgi to run a single app. In this post, I'll show how to configure uwsgi as a system service (with upstart) capable of serving multiple python WSGI compliant web applications by simply placing them in a standard location and adding an standard xml file.
http://jawher.me/2012/03/16/multiple-python-apps-with-nginx-uwsgi-emperor-upstart/
This is a recipe on how to easily run multiple Python web applications using uwsgi server (in emperor mode) and behind nginx. Most existing docs and blogs would show how to manually start uwsgi to run a single app. In this post, I'll show how to configure uwsgi as a system service (with upstart) capable of serving multiple python WSGI compliant web applications by simply placing them in a standard location and adding an standard xml file.
http://jawher.me/2012/03/16/multiple-python-apps-with-nginx-uwsgi-emperor-upstart/
Monday, June 2, 2014
Python WSGI with Node-Webkit
Quote from site :
Let us combine the greatness of HTML/CSS/Javascript for user interface with Python the best way to build backend to create a desktop app.
The basic idea is to use create a python webserver process, wait for it to start and display your app. After your app closes it will close the webserver process.
http://blog.infireal.com/wsgi-node-webkit-2014-03.html
Let us combine the greatness of HTML/CSS/Javascript for user interface with Python the best way to build backend to create a desktop app.
The basic idea is to use create a python webserver process, wait for it to start and display your app. After your app closes it will close the webserver process.
http://blog.infireal.com/wsgi-node-webkit-2014-03.html
Wednesday, May 28, 2014
Single-File Stand-alone Python 2.7.5 for Windows
If you don't want to install Python on your client.
Here is a solution :
Quote from site :
I frequently write programs in python as it is a handy, powerful language. However, sometimes I don't want to install it. There are some other projects to give a portable python implementation. That still seems too heavy for some tasks.
Here is a Windows executable form of Python 2.7.5 that contains most of the standard libraries, plus pywin32. It has the following features:
I've included the very simple source code, which is nothing more than a setup.py script using py2exe. I compressed the executable using upx, which reduces its size by 12% or so and doesn't substantially slow down starting the program.
http://www.orbitals.com/programs/pyexe.html
Here is a solution :
Quote from site :
I frequently write programs in python as it is a handy, powerful language. However, sometimes I don't want to install it. There are some other projects to give a portable python implementation. That still seems too heavy for some tasks.
Here is a Windows executable form of Python 2.7.5 that contains most of the standard libraries, plus pywin32. It has the following features:
- Single file with no dependencies besides Windows (XP or later)
- Can run python programs (e.g.,
py.exe sample_program.py) - Can be used as an interactive shell (e.g.,
py.exe, then start typing) - Can be used to execute string commands (e.g.,
py.exe -c "print 'hello world'")
I've included the very simple source code, which is nothing more than a setup.py script using py2exe. I compressed the executable using upx, which reduces its size by 12% or so and doesn't substantially slow down starting the program.
http://www.orbitals.com/programs/pyexe.html
Book Review: Programming Collective Intelligence in Python
A nice review for a great book
Microsoft Updates Python Tools for Visual Studio
Quote from site
"PTVS," as it's called, includes "integrated IPython REPL support for smart history, shell commands and inline images." It also contains Python-specific tools like mixed mode debugging of Python with C++ and remote debugging of Linux servers in Azure.
http://visualstudiomagazine.com/articles/2014/04/10/python-tools-for-visual-studio.aspx
"PTVS," as it's called, includes "integrated IPython REPL support for smart history, shell commands and inline images." It also contains Python-specific tools like mixed mode debugging of Python with C++ and remote debugging of Linux servers in Azure.
http://visualstudiomagazine.com/articles/2014/04/10/python-tools-for-visual-studio.aspx
Subscribe to:
Posts (Atom)