Python @ DjangoSpin

Python: Running Python Scripts

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 2 minutes

Running Python Scripts

Running Python Scripts: Once you have installed Python, you executed Python scripts (.py files) in the following way:

  • For Windows, press Windows + R for the run dialog, type in cmd and press enter.
  • The command line dialog pops up, now, type python complete_path_to_file.py e.g. python C:\DirOne\file1.py.
  • A handy way to do this entire process is, go into the directory that contains your .py file. Press shift + right click on your mouse > open command window here, then python file.py.
  • You'll see the same output.

The way this works is that the Python keyword invokes the python.exe interpreter which executes your .py file. If you want an interactive Python shell in the command window, type in python and press enter. As you can see, it provides the same window as in IDLE.

  • For Mac users, go into the terminal, navigate into your working directory (that is, the directory you have chosen to keep your learning Python files in)
  • Type in touch file.py, edit it with vi or nano by vi name_of_file.py or nano name_of_file.py
  • Give permissions to your user to execute the script by chmod 777 file.py
  • Then typing python file.py in the terminal will execute it.

The location of Python interpreter in Mac and linux distributions is normally /usr/local/bin/python3. In Windows, it is something like C:\Pythonxx\python.exe if you accepted defaults, this address may vary if you installed it somewhere else and/or if you installed a different version of Python.

If you execute a .py file (containing, say, a single print statement) by double clicking on it, then you will notice that a console window opens for a brief moment, and then it vanishes. In fact, it would have vanished too quickly for you to read anything printed on the screen. There are two ways for making the screen stay till you have read the message in the print statement.

First, after the print statement, in a new line, type input(). Save the file and execute the .py by double-clicking on it. What the input() function does is that it asks for user input.

Second, create a batch file i.e. a .bat file (Windows users), type in python file_name.py, replacing the file_name by your file name and in the second line, type pause. Save this file, and execute it by double-clicking on it. It will produce the same result.

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply