miércoles, 31 de enero de 2018

using python split function

text= 'Ambioirx Rodriguez Placencio'

# splits at space
print(text.split())
print(text.split()[2])


Result it is  list

['Ambioirx', 'Rodriguez', 'Placencio']
Placencio

martes, 30 de enero de 2018

JSON encoding and decoding with Python



Introduction
JSON (JavaScript Object Notation) is frequently used between a server and a web application. An example of JSON data:
{
    "persons": [
        {
            "city": "Seattle", 
            "name": "Brian"
        }, 
        {
            "city": "Amsterdam", 
            "name": "David"
        }
    ]
}
The json module enables you to convert between JSON and Python Objects.

JSON conversion examples

Convert JSON to Python Object (Dict)
To convert JSON to a Python dict use this:
import json
 
json_data = '{"name": "Brian", "city": "Seattle"}'
python_obj = json.loads(json_data)
print python_obj["name"]
print python_obj["city"]
Convert JSON to Python Object (List)
JSON data can be directly mapped to a Python list.
import json
 
array = '{"drinks": ["coffee", "tea", "water"]}'
data = json.loads(array)
 
for element in data['drinks']:
    print element
Convert JSON to Python Object (float)
Floating points can be mapped using the decimal library.
import json
from decimal import Decimal
 
jsondata = '{"number": 1.573937639}'
 
x = json.loads(jsondata, parse_float=Decimal)
print x['number']
Convert JSON to Python Object (Example)
JSON data often holds multiple objects, an example of how to use that below:
import json
 
json_input = '{"persons": [{"name": "Brian", "city": "Seattle"}, {"name": "David", "city": "Amsterdam"} ] }'
 
try:
    decoded = json.loads(json_input)
 
    # Access data
    for x in decoded['persons']:
        print x['name']
 
except (ValueError, KeyError, TypeError):
    print "JSON format error"
Convert Python Object (Dict) to JSON
If you want to convert a Python Object to JSON use the json.dumps() method.
import json
from decimal import Decimal
 
d = {}
d["Name"] = "Luke"
d["Country"] = "Canada"
 
print json.dumps(d, ensure_ascii=False)
# result {"Country": "Canada", "Name": "Luke"}
Converting JSON data to Python objects 
JSON data can be converted (deserialized) to Pyhon objects using the json.loads()function.  A table of the mapping:
JSONPython
objectdict
arraylist
stringstr
number (int)int
number (real)float
trueTrue
falseFalse
nullNone

Pretty printing

If you want to display JSON data you can use the json.dumps() function.
import json
 
json_data = '{"name": "Brian", "city": "Seattle"}'
python_obj = json.loads(json_data)
print json.dumps(python_obj, sort_keys=True, indent=4)
https://pythonspot.com/en/json-encoding-and-decoding-with-python/

sending email using python without SMTP

import os
os.system("echo \"This is a test\" | mail -s \"Test\" ambiorixg12@gmail.com")

Python Execute Unix / Linux Command Examples

Python Execute Unix / Linux Command Examples

https://www.cyberciti.biz/faq/python-execute-unix-linux-command-examples/

os.system example (deprecated)

The syntax is:
import os
os.system("command")
In this example, execute the date command:
import os
os.system("date")
Sample outputs:
Sat Nov 10 00:49:23 IST 2012
0
In this example, execute the date command using os.popen() and store its output to the variable called now:
import os
f = os.popen('date')
now = f.read()
print "Today is ", now
Sample outputs:
Today is  Sat Nov 10 00:49:23 IST 2012

Say hello to subprocess

The os.system has many problems and subprocess is a much better way to executing unix command. The syntax is:
import subprocess
subprocess.call("command1")
subprocess.call(["command1", "arg1", "arg2"])
In this example, execute the date command:
import subprocess
subprocess.call("date")
Sample outputs:
Sat Nov 10 00:59:42 IST 2012
0
You can pass the argument using the following syntax i.e run ls -l /etc/resolv.confcommand:
import subprocess
subprocess.call(["ls", "-l", "/etc/resolv.conf"])
Sample outputs:
<-rw-r--r-- 1 root root 157 Nov  7 15:06 /etc/resolv.conf
0
To store output to the output variable, run:
import subprocess
p = subprocess.Popen("date", stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
print "Today is", output
Sample outputs:
Today is Sat Nov 10 01:27:52 IST 2012
Another example (passing command line args):
import subprocess
p = subprocess.Popen(["ls", "-l", "/etc/resolv.conf"], stdout=subprocess.PIPE)
output, err = p.communicate()
print "*** Running ls -l command ***\n", output
Sample outputs:
*** Running ls -l command ***
-rw-r--r-- 1 root root 157 Nov  7 15:06 /etc/resolv.conf
In this example, run ping command and display back its output:
import subprocess
p = subprocess.Popen(["ping", "-c", "10", "www.cyberciti.biz"], stdout=subprocess.PIPE)
output, err = p.communicate()
print  output
The only problem with above code is that output, err = p.communicate() will block next statement till ping is completed i.e. you will not get real time output from the ping command. So you can use the following code to get real time output:
import subprocess
cmdping = "ping -c4 www.cyberciti.biz"
p = subprocess.Popen(cmdping, shell=True, stderr=subprocess.PIPE)
while True:
    out = p.stderr.read(1)
    if out == '' and p.poll() != None:
        break
    if out != '':
        sys.stdout.write(out)
        sys.stdout.flush()
Sample outputs:
PING www.cyberciti.biz (75.126.153.206) 56(84) bytes of data.
64 bytes from www.cyberciti.biz (75.126.153.206): icmp_req=1 ttl=55 time=307 ms
64 bytes from www.cyberciti.biz (75.126.153.206): icmp_req=2 ttl=55 time=307 ms
64 bytes from www.cyberciti.biz (75.126.153.206): icmp_req=3 ttl=55 time=308 ms
64 bytes from www.cyberciti.biz (75.126.153.206): icmp_req=4 ttl=55 time=307 ms
 
--- www.cyberciti.biz ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3001ms
rtt min/avg/max/mdev = 307.280/307.613/308.264/0.783 ms

Related media



Raspberry Pi Pyton

http://raspi.tv/2013/rpi-gpio-basics-5-setting-up-and-using-outputs-with-rpi-gpio

https://sourceforge.net/p/raspberry-gpio-python/wiki/Outputs/

http://www.instructables.com/id/Controlling-Multiple-LEDs-With-Python-and-Your-Ras/

http://www.instructables.com/id/Raspberry-Pi-Home-Automation-Control-lights-comput/

https://gist.github.com/FutureSharks/ab4c22b719cdd894e3b7ffe1f5b8fd91

http://raspi.tv/2013/rpi-gpio-basics-6-using-inputs-and-outputs-together-with-rpi-gpio-pull-ups-and-pull-downs

https://www.bouvet.no/bouvet-deler/utbrudd/building-a-motion-activated-security-camera-with-the-raspberry-pi-zero
https://www.raspberrypi-spy.co.uk/2012/06/simple-guide-to-the-rpi-gpio-header-and-pins/
https://www.raspberrypi-spy.co.uk/2012/06/control-led-using-gpio-output-pin/

https://www.raspberrypi-spy.co.uk/2012/06/simple-guide-to-the-rpi-gpio-header-and-pins/#prettyPhoto

https://projects.raspberrypi.org/en/projects/getting-started-with-picamera/8

https://www.jameco.com/Jameco/workshop/circuitnotes/raspberry-pi-circuit-note.html
http://projects.privateeyepi.com/home/on-off-project

https://diyhacking.com/raspberry-pi-gpio-control/

https://www.youtube.com/watch?v=JHbGLlFTXi8

https://www.youtube.com/watch?v=Y2QFu-tTvTI

https://www.youtube.com/watch?v=IP-szuon2Bk
https://www.youtube.com/watch?v=0i2C3Qagosc
https://www.youtube.com/watch?v=6PuK9fh3aL8
https://www.youtube.com/watch?v=gbJB3387xUw
Montion derection
https://www.hackster.io/hardikrathod/pir-motion-sensor-with-raspberry-pi-415c04

https://www.raspberrypi.org/documentation/usage/gpio/
http://raspi.tv/2013/rpi-gpio-basics-5-setting-up-and-using-outputs-with-rpi-gpio

https://sourceforge.net/p/raspberry-gpio-python/wiki/BasicUsage/

https://www.modmypi.com/blog/gpio-and-python-39-blinking-led

http://osoyoo.com/2017/06/26/introduction-of-raspberry-pi-gpio/
https://www.raspberrypi.org/documentation/usage/gpio/

https://www.lifewire.com/light-an-led-with-the-raspberry-pis-gpio-4090226

https://www.hackster.io/user00317224/control-led-using-raspberry-pi-gpio-049a02

https://thepihut.com/blogs/raspberry-pi-tutorials/27968772-turning-on-an-led-with-your-raspberry-pis-gpio-pins
https://computers.tutsplus.com/tutorials/learn-how-to-use-raspberry-pi-gpio-pins-with-scratch--mac-59941


*************


https://www.raspberrypi.org/documentation/usage/gpio/


http://raspi.tv/2013/rpi-gpio-basics-5-setting-up-and-using-outputs-with-rpi-gpio


https://www.jameco.com/Jameco/workshop/circuitnotes/raspberry-pi-circuit-note.html

lunes, 29 de enero de 2018

python ramdom elements from a list and dictionary

import random

foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
For cryptographically secure random choices (e.g. for generating a passphrase from a wordlist), use random.SystemRandom class:
import random

foo = ['battery', 'correct', 'horse', 'staple']
secure_random = random.SystemRandom()
print(secure_random.choice(foo))


import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'}
random.choice(d.keys())
on python
random.choice(list(d.keys())) 

domingo, 28 de enero de 2018

python curl

http://www.angryobjects.com/2011/10/15/http-with-python-pycurl-by-example/

How to get json data from remote url into Python script


To get json output data from remote ot local website,
http://www.powercms.in/blog/how-get-json-data-remote-url-python-script
Method 1
      Get data from the URL and then call json.loads e.g.
      import urllib, json

      url = "http://maps.googleapis.com/maps/api/geocode/json?address=googleplex&sensor=false"

      response = urllib.urlopen(url)

      data = json.loads(response.read())

      print data
    Method 2
      json_url = urlopen(url)

      data = json.loads(json_url.read())

      print data

    Method 3
      check out JSON decoder in the requests library.

        import requests

        r = requests.get('url')

        print r.json()