Category: Python

Set up Python Virtual Envs

No Comments

Developing an application in its own virtualenv is vital. Virtual envs help isolate python envrionments and enable you to install dependant packages in this isolated environment rather than globally.

  1. First find out the version of python you installed. I have python 2.7 default install on MacOS and python 3 via Homebrew package manager for MacOS
  2. Python packages required – virtualenv, virtualenvwrapper.
    pip3 install virtualenv virtualenvwrapper  #pip3 is using python3 interpretor
  3. Virtualenv package enables you to create project/application specific virtual env. Virtualenvwrapper is an extension of Virtualenv. It helps create,manage and delete virtual envs making it easier to work on more than one project at a time eliminating conflicts.
  4. Add the below lines to the ~/.bash_profile


    #tells which interpretor to use. In this case ‘python3’

    VIRTUALENVWRAPPER_PYTHON=’/usr/local/bin/python3′
    #set the env variable and assign a path to create projects

    PROJECT_HOME=’/Users/chetanak/Box Sync/Projects’

    #reload script
    source /usr/local/bin/virtualenvwrapper.sh

    #Exports the varible and makes available the previous and the new env to all the processes. All the virtual envs are stored under ‘.virtualenvs’ folder in your home directory
    export WORKON_HOME=$HOME/.virtualenvs

  5. Save the above file and run these commands

    mkdir ~/.virtualenvs

    #Load your ~/.bash_profile with the new changes.
    source ~/.bash_profile

  6. Now that all the paths and directories are created and set, you can create your virtual environments. Simply use –

    mkproject <projectname>

    #This creates a virtual env with the name of the project under ~/.virtualenvs directory and also create the project directory with the same name under $PROJECT_HOME. Since we are using the virtualenvwrapper functions, upon creation, it will activate the virtual env and ‘cd’ into the project folder

  7. To deactivate the virtualenv type ‘deactivate’ at the prompt
  8. If you want to know more about the virtualenvwrapper commands go to – http://docs.python-guide.org/en/latest/dev/virtualenvs/

Read More

Setting the ENV to run WLST scripts remotely

No Comments

1. Install Java, Python, Jython. Set path for each installation.

2. Download the Zip distribution for Oracle WebLogic Server only that is intended for Weblogic Server development. At the time of this writing, I have Weblogic server version 10.3.5. The zipped version is about 180MB and very light. Unzip the contents.

4. Inorder to setup the ENV you need to run setWLSEnv.cmd or .exe file depending on your OS. This file is located under your weblogic installation folder – “C:\wlserver\server\bin”

5. If you get errors while running file, then open the file setWLSEnv.cmd and make sure the paths that this file needs are set in your environment variables. If you don’t have them, set them and re-run the file. You should see a message confirming that your environment has been set.

6. To run your WLST scripts you need to set the env in the shell first. Followed by the command “java weblogic.WLST filename.py

Categories: Jython, Python, WLST

My reference notes on Python

No Comments

1. Data types

  • int
  • float
  • string – can contain letters, numbers and symbols. String needs to be within quotes.
  • unicode – a special type of string
  • boolean – takes the values “True” or “False”
  • list – enclosed in square braces
  • dictionary –they have key value pairs. Pairs are enclosed in curly braces

2. Comments

# Prefix a hash for a single line comment

“”” Enclose multi   line  comments                                                                                                                                                       between triple quotation marks”””

3.  Arithematic Operations – +, -, *, /, **, %

4.  Comparision operators: ==, <=, >=, >, <, <>, !=

      Comparision operators results in a “True” or “False” values and the result of comparision can be stored in a variable.

5.  There are three boolean operators and the are listed here in the ORDER they are operated: not, and, or

6.  Broken String can be fixed by using the escape backslash!

  • ‘This isn\’t flying, this is falling with style!’

7.  String is like a List. A character in the string can be extracted by the index value beginning with 0 and starting from the left of the string. For ex.

varString = “Python”

# Print the 4th letter.

fourth_letter = “Python”[3]

print fourth_letter

8.  Slice a String or List, by using the index values

varString = “Python”

# Print the first 3 characters.

fourth_letter = “Python”[3]

print fourth_letter

9.  Built-in string functions

  • len()
  • str()
  • lower()
  • upper()
  • isalpha()

str() and len() can work on other data types. str() converts the data types to String.    lower()and upper() are used with a dot notation and can only work on strings

10.  built-in functions for int and float types

  • max()
  • min()
  • abs()

11. type(), is a buil-in function that outputs the type of the data type.

print type(13)

#The above prints <type ‘int’> to the console

12. Few examples for PRINT statements

# Print the concatenation of “Good Morning World”
print “Good” + “Morning” + “World”

string_1 = “Hello”
string_2 = “World”

print “Let’s be nice and say, %s %s.” % (string_1, string_2)

Use the % operator to replace the %s placeholders with the variables in parentheses. We need the same number of %s terms in a string as the number of variables in parentheses

13.  To accept the input from the console

name = raw_input(“Enter your name:”)

14.  A list of few Python modules

  • datetime
  • math
  • random

15.  Few syntaxes and declarations

  • define a function – def function():
  • Generic Import – import module
  • Function Import – from module import function
  • Universal Import – from module import *

16. Listing all the functions from a module after the import

import math

list_all = dir(math) # Sets list_all to a list of things from math
print list_all       # Prints all available functions

17.  List manipulation functions. Prefix each with the listname.

  • append()
  • extend()
  • index(item)
  • insert(index, item)
  • sort()
  • remove(item) – will remove the actual item if it finds it
  • pop(item) – will remove the item at index from the list and return it
  • del(listname[index]) – same as pop() but will not return it
  • join()
  • split()

18.  Dictionary items are deleted by – del keyword. Ex. del dictionaryname[key]

19.  range(), function is a shortcut for generating a list.

  • range(stop) –> range(5)
  • range(start, stop) –>range(0, 10)
  • range(start, stop, step) –> range(0, 4, 2)
  • my_list = [I, for I in range(11) if i%2 == 0] # This prints out the even numbers between 0 and 11
  • squares = [i**2 for i in range(1, 11)]  # Another way to create a list

20.  For loop syntax

  • for eachitem in listname:
  • for key in dictionaryname:
  • for i in range(len(list)):

21. List Slicing

  • my_list[start: end: stride]

Note that the default index starts at 0. The default end index is the last element in the list. Stride is the space between items in the sliced list. A positive stride value traverses the string from left to right. The negative stride value traverses the string from right to left.

22.  Python also allows functions to be passed as variables and values

print filter(lambda x: x % 3 == 0, my_list) 

# Here filter uses Lambda to determine what to filter. Lambdas are a quick way to create functions. But if you want to reuse a function, then it is better if you declare it by using “def

23.    Printing items in a dictionary

  • print my_dict.keys()
  • print my_dict.items()
  • print my_dict.values()
Categories: Python