Monday, 20 June 2011

Python : Script mode

We have already discussed that python is an interpreted language and mainly there are two ways to use the interpreter , i.e Interactive mode & Script modes . In the interactive mode it just displays the result of expressions , We can have the python interpreter to execute our script file also.


In script mode we can store the code in a file and use the interpreter to execute the content of the file which we called a script.The scripts must have saved with the extension .py.


To edit the scripts, you can have common editors like gedit , VIM ,eric4 and eric5 etc , Several type of editors are available for Unix and Windows.


But when you edit python scripts the indentation must be accurate, In all our files we use 2-spaces as the indent and 4-spaces is another popular choice.


Script mode

There are several ways to use the interpreter and have execute our scripts.


  • Explicit Command line execution:
Here python script is executed by providing the script file name as parameter to the python interpreter.In this style we explicitly name both the interpreter and the input script.
we have a sample python script file called sample.py is shown below.When you type python sample.py ,it will provide sample.py file to the python interpreter for execution.




You could see an import statement on top of the program ,by using this syntax you can pass command line arguments,i.e sys.argv[1] will print the argument that you passed along with the file name.
if __name__ == '__main__' is the boilerplate syntax to call the function main().It is mainly used when a python file is run directly.


Output of the following program is displayed below .




  • Implicit command line execution:


We can make the script file itself  executable and directing the shell to locate the python interpreter.For windows we can associate our script file .py with python.exe .There are one or two steps to do this.


  • when you creating a script file make sure that first line of the file contain the following #!/usr/bin/env python.
   If you enter the above code, the whole file will look as follows.



  • For POSIX-standard operating systems,do chmod +x sample2.py to make the file sample2.py executable. 
  • Then you can run the file by using ./sample2.py command.
when you run the file ,you will get the expected output as follows.





Thank You..

No comments:

Post a Comment