Pages

Sunday, January 22, 2012

Creating Script files using Python

Open a terminal by pressing Ctrl+Alt+t or Applications->Accessories->Terminal

create a file which you want to make script. In python, create files with py as extension or just the name.
vim filename.py
now after creating the file. Code the file with program you want to use in the script. For example, i am creating an echo function which prints whatever we give.
#!/usr/bin/python
a=raw_input()
print a

save the file as usually by pressing esc and the semicolon followed by wq. After saving the file change permission of file by typing the below code
chmod -c 777 filename.py
since the executable files like cp, ls, mkdir etc are saved at /bin/ location. Thus paste the file in the bin folder as super user mode.
sudo cp filename.py  /bin/
Type your root password when asked. Now after that, the original file filename.py is still in your directory, so please remove or move it to another location. Instead of cp, you can use mv(move) in the above command, if you want to move the original file. Now just type the filename only.
filename.py
you can use just filename without any extension for creating python files, since it works. For eg:
vim filename
Thus, now you just have to enter only the filename.
Note : Keep in mind, the line in the code " #!/usr/bin/python " is important since it shows the python location in your system to the python interpreter, so that while running python files, you need not have to use python command before your file and also very important while running python scripts.
For more details on python programming, you can check python program section in the Python programming Basics post of mine. Same way, you can also create such executable files using C program, for further details on C executable files visit http://amithkp.wordpress.com/2012/01/04/executable-file-creation-in-c/ .

No comments:

Post a Comment