dilluns, 26 de febrer del 2018

Threading in Python

Very very similar to Java but with less code. 

import threading
import datetime
import time

DELAY = 10

def hacertrabajo():
timeinit = datetime.datetime.now()
print("se inicia "+str(timeinit))
time.sleep(10)
print("se finaliza "+ str(datetime.datetime.now()) + "en "+str(datetime.datetime.now()-timeinit))

th1 = threading.Thread(target=hacertrabajo,name="th-1")
th2 = threading.Thread(target=hacertrabajo,name="th-2")

th1.start()
th2.start()


print("no se espera")

if you execute the prgoram you will see that the output "no se espear" is writtein even without having finisthed both threads.

PS C:\Users\jordi\Documents\python\multithread> python multi.py
se inicia 2018-02-26 22:02:26.326352
start th1
se inicia 2018-02-26 22:02:26.328306
start th2
no se espera
se finaliza 2018-02-26 22:02:36.328301en 0:00:10.001949
se finaliza 2018-02-26 22:02:36.330257en 0:00:10.001951

to wait implement the call join(seconds) where seconds are the timeout , the time point the time when the control will arive to point join

import threading
import datetime
import time

DELAY = 10

def hacertrabajo():
timeinit = datetime.datetime.now()
print("se inicia "+str(timeinit))
time.sleep(10)
print("se finaliza "+ str(datetime.datetime.now()) + "en "+str(datetime.datetime.now()-timeinit))

th1 = threading.Thread(target=hacertrabajo,name="th-1")
th2 = threading.Thread(target=hacertrabajo,name="th-2")

th1.start()
th2.start()
timeinit = datetime.datetime.now()
th1.join(5)
print("se finaliza th1 "+ str(datetime.datetime.now()) + "en "+str(datetime.datetime.now()-timeinit))
th2.join(11)
print("se finaliza th2"+ str(datetime.datetime.now()) + "en "+str(datetime.datetime.now()-timeinit))

Da el resultado siguiente.

PS C:\Users\jordi\Documents\python\multithread> python multi.py
se inicia 2018-02-26 22:22:31.651966
se inicia 2018-02-26 22:22:31.652945
se finaliza th1 2018-02-26 22:22:36.653236en 0:00:05.000291
se finaliza 2018-02-26 22:22:41.653288en 0:00:10.001322
se finaliza 2018-02-26 22:22:41.654265en 0:00:10.001320
se finaliza th22018-02-26 22:22:41.655247en 0:00:10.002302
PS C:\Users\jordi\Documents\python\multithread>

Tal y como indica la documentacion lo normal de join() seria despues hacer algo con el thread como

dissabte, 17 de febrer del 2018



PlyGround with Python 1

how easy is python and sqlite3

import sqlite3
import datetime

def createDataBase():
conn = sqlite3.connect('control.db')
c = conn.cursor()
c.execute('create table control( nombre TEXT, fechaini timestamp, fechafin timestamp)')
c.close()

def pupulateDataBase():
conn = sqlite3.connect('control.db')
c = conn.cursor()
c.execute('insert into control values (?,?,?)',('registro 1',datetime.datetime.now(),datetime.datetime.now()))
conn.commit()
conn.close()

def pupulateDataBaseWhitNull():
conn = sqlite3.connect('control.db')
c = conn.cursor()
c.execute('insert into control values (?,?,?)',('registro 1',datetime.datetime.now(),None))
conn.commit()
conn.close()
def fetchDataBase():
conn = sqlite3.connect('control.db')
c = conn.cursor()
for row in c.execute('SELECT * FROM control'):
print(row)


createDataBase()
pupulateDataBase()
pupulateDataBaseWhitNull()
fetchDataBase()


(test) C:\Users\jordi\jordi\workspaces\python\test>python testsqlite.py
('registro 1', '2018-02-17 10:48:47.235088', '2018-02-17 10:48:47.235088')
('registro 1', '2018-02-17 10:48:47.354523', None)


LightWeight Python Envirotment with Visual Studio 

Create a virtualenv with virtualenv and later activate it running the activate script.

Open the VSC and creaate a fill called .env with the variable PYTHONPATH pointing to the site-packages where the virualenv located all the libraries already download by PIP.

PYTHONPATH=C:\Users\jordi\jordi\workspaces\python\test\Lib\site-packages




diumenge, 11 de febrer del 2018



Little’s law

number of threads = (Requests/sec) X (ResponseTime in secs)

dissabte, 3 de febrer del 2018

ssh keys


From my laptop I will create the keys and I will expose this key to the server I want to connect using keys. Additionally we get rid of passwords , even for my user as sudo user.

jordi@LAPTOP-ELFAQNCG MINGW64 ~/.ssh
$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/jordi/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /c/Users/jordi/.ssh/id_rsa.
Your public key has been saved in /c/Users/jordi/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:ljvEge2a/MwKp8OK73ai27v7zRFiPyPmMxJCpw0nJLU jordi@LAPTOP-ELFAQNCG
The key's randomart image is:
+---[RSA 2048]----+
| ..              |
|.. .   o         |
|o E   . o        |
| + o   o o       |
|. B o . S        |
|...o + * .       |
| . o+ X o        |
| o+o*B B .       |
|+*OX+++.+        |
+----[SHA256]-----+

jordi@LAPTOP-ELFAQNCG MINGW64 ~/.ssh
$ ssh-copy-id jordi@localhost
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/c/Users/jordi/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
no such identity: /c/Users/jordi/.ssh/keys/id_rsa.pub: No such file or directory
jordi@localhost's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'jordi@localhost'"
and check to make sure that only the key(s) you wanted were added

jordi@LAPTOP-ELFAQNCG MINGW64 ~/.ssh
$ cat config
Host localhost
 Hostname localhost
 IdentityFile ~/.ssh/id_rsa
.

jordi@LAPTOP-ELFAQNCG MINGW64 ~/.ssh
$ ssh localhost
Last login: Sat Feb  3 17:27:47 2018 from gateway
[jordi@localhost ~]$

At centos to avoid password for instance to avoid pas to do sudo

/etc/ssh/sshd_config
PasswordAuthentication no

addl to the bototn
 sudo visudo
jordi ALL=(ALL) NOPASSWD: ALL