miércoles, 14 de febrero de 2018

Try and Except in Python


Earlier I wrote about Errors and Exceptions in Python. This post will be about how to handle those. Exception handling allows us to continue our program (or terminate it) if an exception occurs.

Error Handling

Error handling in Python is done through the use of exceptions that are caught in 
try blocks and handled in except blocks. 

Try and Except

If an error is encountered, a try block code execution is stopped and transferred
down to the except block. 

In addition to using an except block after the try block, you can also use the
finally block. 

The code in the finally block will be executed regardless of whether an exception
occurs.

Raising an Exception

You can raise an exception in your own program by using the raise exception 
[, value] statement. 

Raising an exception breaks current code execution and returns the exception
back until it is handled.

Example

A try block look like below
try:
    print "Hello World"
except:
    print "This is an error message!"

Exception Errors

Some of the common exception errors are:

IOError
If the file cannot be opened.

ImportError
If python cannot find the module

ValueError
Raised when a built-in operation or function receives an argument that has the
right type but an inappropriate value

KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete)

EOFError
Raised when one of the built-in functions (input() or raw_input()) hits an
end-of-file condition (EOF) without reading any data

Example

Let's have a look at some examples using exceptions. 
except IOError:
    print('An error occured trying to read the file.')
    
except ValueError:
    print('Non-numeric data found in the file.')

except ImportError:
    print "NO module found"
    
except EOFError:
    print('Why did you do an EOF on me?')

except KeyboardInterrupt:
    print('You cancelled the operation.')

except:
    print('An error occured.')

There are a number of built-in exceptions in Python. 
http://www.pythonforbeginners.com/error-handling/python-try-and-except

domingo, 4 de febrero de 2018

while True:

#!/usr/bin/env python

import sys


while True:

    n = raw_input("Please enter your 'skill':")


    if n.strip()== "php" :

       print("you re a web developer")

    if n.strip()== "exit" :

      print("Good bye !")

      sys.exit()

    else:

       print("you re not a web developer")


While loops

Usage in Python

  • When do I use them?
While loops, like the ForLoop, are used for repeating sections of code - but unlike a for loop, the while loop will not run n times, but until a defined condition is no longer met. If the condition is initially false, the loop body will not be executed at all.
As the for loop in Python is so powerful, while is rarely used, except in cases where a user's input is required*, for example:
n = raw_input("Please enter 'hello':")
while n.strip() != 'hello':
    n = raw_input("Please enter 'hello':")
However, the problem with the above code is that it's wasteful. In fact, what you will see a lot of in Python is the following:
while True:
    n = raw_input("Please enter 'hello':")
    if n.strip() == 'hello':
        break
As you can see, this compacts the whole thing into a piece of code managed entirely by the while loop. Having True as a condition ensures that the code runs until it's broken by n.strip() equaling 'hello'.

  • Another version you may see of this type of loop uses while 1 instead of while True. In older Python versions True was not available, but nowadays is preferred for readability.
  • https://wiki.python.org/moin/WhileLoop

viernes, 2 de febrero de 2018

python classes basic

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'
x = MyClass()
print(x.f())




class Dog:

    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name):
        self.name = name    # instance variable unique to each instance
d = Dog('Fido')
print(d.name)
print(d.kind)
e = Dog('Boby')
print(e.name)
print(e.kind)

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