Executing Python

A place where you can post Python-related tutorials you made yourself, or links to tutorials made by others.

Executing Python

Postby metulburr » Thu Feb 07, 2013 11:56 pm

How to Execute python code

There are 3 main ways to execute a python script.
1) Interactive Prompt
2) IDE (Python script)
3) Command Line (Python script)

*How you execute the code also depends on the version. Code written for python2.x may not always execute without traceback errors in python3.x. So the syntax is NOT always the same, nor not always importing the same modules. If your not sure how to find your version, check here. The differences between the two versions can be found here. You may also have to change your IDE's settings to select a different python version from the default, if you have multiple python versions installed.

Interactive Prompt

This is mostly used for experimenting and testing. Although you can write out long codes here, you should switch over to a file if you plan to write more than 3-5 lines. An IDE or file would be more appropriate and easier. The >>> is the prompt for interactive mode. What you type here is python code. Unlike the other methods of executing python, It will be executed right after you hit Enter, upon each line. The only time it does not execute after Enter (or each line) is when you are defining a function or class or a loop, for example. The ... will indicate that you are inside the block of what you are defining. **Some IDE's do not have the ..., in which it is advised to find a different IDE at that point. Once you finish writing the code inside the block, you must hit Enter twice, where it will execute and take you back to the >>> prompt depending on what you are defining.

The reason the interactive prompt is for testing is because:
1) it will execute upon each line or after the definition of a loop, class, function, etc.
2) Once you exit the interactive prompt, what code you wrote in it, is gone. There is no saving the code.

The other two methods of executing python code will save a file with your code in it.



Windows

In Windows 7 or less than, Click on Start Menu -> (on search) type: "command prompt". A Black icon "cmd" or Command prompt" will show up. Or open c:\Windows\system32\cmd.exe which will do the same. In windows 8, just type "cmd" in the menu, which should enable search, and pull of an icon of hte command console. This is a DOS prompt. You can do everything you can do normally on the PC in this DOS prompt with commands. The text before your cursor is the directory you are currently in. The command "cd" will change your current directory to the string after. The command 'dir' will list the directories in that directory that you are in. PythonXX should be in the directory C:\PythonXX (where XX represent the version you have downloaded). Once in the directory: type "python" to execute the interactive prompt.

Code: Select all
C:\Windows\system32>cd c:\Python32

C:\Python32>python
Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 ...
Type "help", "copyright", "credits" or "license" for more information.
>>>


If you see ">>>", then you are in in the python interactive prompt.

However this will only execute python code in the directory C:\Python32.

Are you getting this Error?
Code: Select all
python is not recognized as an internal or external command,
operable program or batch file.

This will make the Python executable runable from anywhere, not any script. If the script lives in a different directory than where you are at, you still need to change to that directory, or give the full path of that file to execute it.
To make python execute in any directory in Windows. You have to add python to the PATH environmental variable. To get there:
[Window 7] My Computer (right-Click) > Properties > Advanced System Settings > Environmental Variables > Under System Variables > double click Path > append python directory path to this, separated by semicolons (see below). Click OK to all the windows you have up.
[Windows 8] Go to Metro or Start and just type in "Advanced System Settings" > Environmental Variables > Under System Variables > double click Path > append python directory path to this, separated by semicolons (see below). Click OK to all the windows you have up.
Youtube screencast

For the example above using Python32. In environmental variables there is a path varaible already existing
i changed the path variable from:
Code: Select all
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\

to
Code: Select all
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Python32

So i appended to the variable
Code: Select all
;C:\Python32
, the full path of Python32 separated with the other variables with a semi-colom

After that, OK out of all those windows, kill the command console and get a fresh command console with the same method you did before. However, this time, you will notice that you can change directory into any directory, and the command python will pull up the interpreter. An easy indicator that you were successful.

an example output:
before setting the path:
Code: Select all
C:\Users\metulburr>python
'python' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\metulburr>cd Python32

C:\Users\metulburr\Python32>python
Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

C:\Users\metulburr\Python32>cd ..

C:\Users\metulburr>python
'python' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\metulburr>

refresh the console
after setting the path:
Code: Select all
C:\Users\metulburr>python
Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on wi
32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

C:\Users\metulburr>cd C:\

C:\>python
Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on wi
32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

C:\>



To do that in command prompt:
Code: Select all
set PATH=%PATH%;C:\My_python_lib
To add permanently add that path to autoexec.bat.


Linux

Open a Terminal. It does not matter what directory you are in. If you have both python2.x and python3.x installed, you can use either interactive prompt by a number. "python" is the default for your OS. The default may be python3.x in some distros (currently now is gentoo and arch)

python2.x
Code: Select all
metulburr@ubuntu:~$ python
Python 2.7.3 (default, Aug  1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>


python3.x
Code: Select all
metulburr@ubuntu:~$ python3
Python 3.2.3 (default, May  3 2012, 15:51:42)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>


depending on your linux distro and time as more and more distros use python3.x as default in the comming years, python3.x may be default where python referes to 3.x and python2 referes to 2.x

IDE
An IDE is just a fancy text editor. That's it. It does not perform magic tricks. You can accomplish the same without ever installing an IDE. See below for Command line / Terminal as this does just that. The bare bones of an IDE just creates a file and puts your text in that file, with a button to execute it. There are numerous IDE's. The only difference is preference. Some are free and some are not, but give out a free version that will work.

Each IDE is different in how you configure it, execute code, etc. Some have a run command, and F# key, Ctrl+b, etc. to execute the python code. Some will open a terminal/console with for the output, some will have embedded terminals, and some will have their own area for output. Some will have all of these options, some will have only a few of these options. All IDE's can be re-configured to your liking.For example: If you don't like that F5 runs your code, you can change the keybinding to Ctrl + b, or vice-versa. If you want an embedded terminal in the IDE and the IDE doesn't do it by defualt, chances are there is a plugin for that IDE that will allow it. And so on and so on.

What is IDLE? IDLE is just only one of the numerous IDE's. Just because python on windows comes with IDLE, does not mean python needs IDLE to run. It is there for beginner's convenience. Also by most programmers, it is also considered one of the worst IDE's too. It shall be fine for beginner's though. You can research why with a google search later, or run across the reasons yourself as you progess in programming. For those that stick with IDLE, IDLE starts you off with the python interpreter. This is not a command line! It is just a GUI form of the python interpreter that you can also get in the command line/terminal. It confuses a lot of beginner's because they think they click new window, write their code, and run their code in the python interpreter, thinking it is a command line or terminal. File -> New Window creates an empty file in the same way that Notepad does. And Run -> Run Module executes this code. The output of the code (at least in IDLE) is displayed amongst the python interpreter as opposed to a terminal, AKA ('>>>'). And the python interpreter is there for a quick one liner tests here and there, not to run the code you saved in the new window.
*IDLE is also one of the IDE's that does not show the ... in the embedded interpreter for indentation. It is advised to find another IDE or use the command line, if you use the interpreter a lot.

If you are confused on the process of using an IDE, or if you still think python requires idle to run, then install some other IDE's and use them for awhile. Try at least 5 of them out. In addition to that, open and write a file in notepad, and execute it in the command prompt. Then create a file, write in the file, and execute that file all in the command prompt all without using an IDE or GUI text editor. At this point you may start to understand the concept.

Command Line / Terminal
More often than you think, people will not use an IDE. In this case you open any text editor you want, write code, and when you save it you save it with the file extension of ".py". An IDE is just a fancy text editor, that's it! You can use anything, Gedit, notepad, IDLE, whatever to write the code. All IDE's have a way of quick run, but you can also run them from the terminal/DOS as shown below.
Code: Select all
test.py

For Windows simplicity: put this test.py file in your directory that you started the interactive prompt: for example of the path:
Code: Select all
c:\Python32\test.py

and example of the same path executed:
Code: Select all
c:\Python32>python test.py

Then you open a Terminal/DOS prompt and change directory to your test.py and write this:
Code: Select all
python test.py



The same as before like with the interactive prompt, but this time we add a argument and the argument is your .py file.

So in short, you can either change to the directory that the file lives in and execute it from there:
Code: Select all
C:\>cd C:\my_python_lib
C:\my_python_lib>python.exe test.py

or you can execute it from any directory if you give the full path of the file:
Code: Select all
C:\>python.exe C:\my_python_lib\test.py


Does your program when executed just flicker and then go away? Most Windows users have got accustomed to double clicking an icon and have it execute. To adjust the program for double clicking, the basic method is to add the builtin input to have it ask the user for "nothing" to assure that the user must hit ENTER before the program closes out. raw_input() for Python 2.x and input() for Python 3.x. Just put this after your program at the end of the file and it will restrict the program to prematurely exiting. This is however only effective if you plan to execute the program by double clicking it. If you use a command line/Terminal to execute the program, you do not need the input function as the command line will still allow you to view the output of your program even after exiting, as you just get the users prompt when it exits.

Linux
Code: Select all
metulburr@ubuntu:~$ touch tester.py
metulburr@ubuntu:~$ vim tester.py
metulburr@ubuntu:~$ cat tester.py
print('this is a test')
metulburr@ubuntu:~$ python3 tester.py
this is a test
metulburr@ubuntu:~$

This example shows the creation and execution of a one line python script. 'touch tester.py' creates the file, although vim will create it anyways. 'vim tester.py' opens one of the numerous text editors. Remember, you can use anything. 'cat tester.py' shows the content of the .py file that i wrote in it, in vim. 'python3 tester.py' executes the script I made with python3.x. 'this is a test' is the output of that program executed.

Command line commands
It depends on what OS you are on as to what the commands are. Some basics are:
Code: Select all
cd something

to change directory to the the directory something (assumeing the file is named 'something'). Of course if that file was nested in another file, you first have to change to that directory (file), then to this one.

Code: Select all
ls

to list the current directory contents in LInux

Code: Select all
dir

to list the current directory contents in Windows

Interactive prompt help()
while in the interactive prompt, you can use the help function to show the documentation for that specific module. For 3rd party modules you have installed you must import it and then help(your_module), it will show a description, classes, functions, version number, author. For builtins it will show class and methods and description of each method, etc.

default help screenclass, methods,
Code: Select all
>>>help()


import module and help()
Code: Select all
>>>from bs4 import BeautifulSoup
>>>help(BeautifulSoup)
>>>import urllib
>>>help(urllib)


show me the documentation for strings
Code: Select all
>>>help(str)


show the specific method s.find()
Code: Select all
>>>help(str.find)


show all modules installed for this version of python
Code: Select all
>>>help('modules')


Resources
IDE's
Python Integrated Development Environments (IDE). A list of of IDE's and info about them.

Internet Relay Chat (IRC) - an IRC channel that is friendly and helpful
When you ask a question the first time, if no one is chatting, wait for up to maybe 2 hours before closing out as to give us time to see it. 3 Minutes is not enough as we are not sitting there all day staring at IRC waiting every second for everyone to ask questions.
IRC in Browser
SERVER: irc.freenode.net
CHANNEL: #python-forum

Official python site
Python tutorials
Download python versions, tutorials, information

PEPS
Information for python, for example PEP 8 is guidlines for style in coding Python.

Online Interpreter
Test Python without installing it

Porting Guide
Check the different modules for 2.x versus 3.x

Modules ported to Python3.x
View 3rd party modules and see if they have been ported to Python 3.x yet. Even if the module you are looking for does not support Python 3.x, there may be methods to tinker it to work, BETA testing, etc. that you can use to get it working still. Google and research and you just might be surpirsed what people have accomplished.

Some 3rd party modules
Django
Web framework for python.

Bottle
Lightweight web framework for python

BeautifulSoup
Parse HTML with Python

wxPython
PyQt
GUI Libraries for Python. There is also tkinter which comes with python (most of the time)

PyGame
2D gaming Library for python

PyOpenGL
3D Library

cx_freeze
package your apps with their dependencies

py2exe
package your apps for Windows users

Avoiding massive elif statements
the first example shows elif statments as you would learn them in any tutorial, the second however shows the same thing done but with no elif statments. It does the same thing but reduces the code and makes it more debugable in the future.
Code: Select all
choice = input('enter a number')
if choice == '0':
   print('you chose zero')
elif choice == '1':
   print('you chose one')
elif choice == '2':
   print('you chose two')
elif choice == '3':
   print('you chose three')
else:
   print('out of range/invalid')


Code: Select all
user_choice = {'0':'zero','1':'one','2':'two','3':'three'}
choice = input('enter a number')
try:
   print('you chose {}'.format(user_choice[choice]))
except KeyError:
   print('out of range/invalid')
Last edited by metulburr on Fri Jun 06, 2014 4:44 am, edited 35 times in total.
Reason: Split out the Debugging part into its own topic
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1383
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: python help

Postby joneshf » Fri Feb 08, 2013 5:34 am

metulburr wrote:
Code: Select all
user_choice = {'0':'zero','1':'one','2':'two','3':'three'}
choice = input('enter a number')
try:
   print('you chose {}'.format(user_choice[choice]))
except KeyError:
   print('out of range/invalid')



I skimmed the vast majority of this, but definitely a great post to start the new forums off with. Can I make this suggestion?

Code: Select all
user_choice = {'0':'zero','1':'one','2':'two','3':'three'}
choice = input('enter a number')
print('you chose {}'.format(user_choice.get(choice, 'an invalid choice')))


Or something similar. Where get takes a default, and removes the need for try/catch.
joneshf
 
Posts: 8
Joined: Thu Feb 07, 2013 3:48 pm

Re: python help

Postby metulburr » Mon Feb 11, 2013 4:42 am

New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1383
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Executing Python

Postby mouseroot » Sun Feb 17, 2013 3:29 pm

something I thought may fit here
when using try and except
Code: Select all
try:
    someInvalidFunc()
except NameError,err:
    print "Cannot find function",err


If you would like to catch invalid function calls
typically great for typos then catching NameError
is your best friend
(perfect for the beginner)
mouseroot
 
Posts: 17
Joined: Sat Feb 16, 2013 1:14 am

Re: Executing Python

Postby Mekire » Fri Feb 22, 2013 2:03 am

mouseroot wrote:something I thought may fit here
when using try and except
Code: Select all
try:
    someInvalidFunc()
except NameError,err:
    print "Cannot find function",err


If you would like to catch invalid function calls
typically great for typos then catching NameError
is your best friend
(perfect for the beginner)


Although I really don't think this does belong here, since you brought it up, I really disagree with this. If someone makes a typo the program shouldn't catch the exception and continue. The interpreter will Raise a NameError automatically and tell the user exactly what they need to know. Exceptions shouldn't be caught in order to allow for bad/sloppy programming. They should be caught for a reason.

Code: Select all
>>> agh = 5
>>> print(ag)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'ag' is not defined
Seems pretty clear to me.

-Mek
User avatar
Mekire
 
Posts: 986
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Executing Python

Postby metulburr » Fri Feb 22, 2013 4:45 am

mouseroot wrote:something I thought may fit here

Yeah, This thread is about Executing Python scripts. joneshf posted a method of doing it another way... of a snippet already in the post. Your post had nothing to do with executing Python or a correction or modification of the original post. So i do not see why it would fit there. And i also agree with Mekire.
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1383
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Executing Python

Postby Yoriz » Fri Feb 22, 2013 6:37 am

mouseroot wrote:something I thought may fit here
when using try and except
Code: Select all
try:
    someInvalidFunc()
except NameError,err:
    print "Cannot find function",err


If you would like to catch invalid function calls
typically great for typos then catching NameError
is your best friend
(perfect for the beginner)


Exceptions will be covered by there own tutorial.
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 776
Joined: Fri Feb 08, 2013 1:35 am
Location: UK


Return to Tutorials

Who is online

Users browsing this forum: No registered users and 1 guest