Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Thursday, April 4, 2013

What's the difference between "import" and "from...import *" in Python?

"import <ModuleName>" loads a Python module into its own namespace and restricts direct access to the members of the module. The references can be accessed by prefixing the module name followed by a dot.

import sys
sys.exit()

On the contrary, "from <ModuleName> import *" loads a module into the current namespace and allows to access those references without a prefix.

from sys import *
exit()

Monday, March 11, 2013

How could you connect Oracle and Python?


#!/usr/bin/python

import os
import cx_Oracle

SQL_STMT="SELECT * FROM TABLE_NAME"

# set Oracle Environment variables in case it has not been
os.putenv('ORACLE_HOME', '/oracle/product/10.2.0/db_1')
os.putenv('LD_LIBRARY_PATH', '/oracle/product/10.2.0/db_1/lib')

connection = cx_Oracle.connect('userid/password@127.0.0.1:1521/SID')

cursor = connection.cursor()
cursor.execute(SQL_STMT)
for row in cursor:
    print row

cursor.close()
connection.close()

How could you swap values of variables in Python?


#!/usr/bin/python
   
a = 5
b = 6

print "Before Swapping : a =", a , "b =", b
a, b = b, a
print "After Swapping : a =", a , "b =", b

Wednesday, January 23, 2013

Monday, January 21, 2013

How could you run UNIX commands in Python?

#!/usr/bin/python
import os
os.system("ls -l")

or

import os
buffer=os.popen("ls -l")
for i in buffer.readlines():
     print "Result:",i,

or

from subprocess import call
call(["ls", "-l"])