How to run python code in terminal

How To Run Python Scripts From the Command Line (Terminal)

This article will demonstrate how to get a simple Python script running on the command line in a matter of minutes. Once you’ve mastered that, you can get more complicated by passing in required arguments so that your scripts can stand on their own. Once you are comfortable running Python scripts from the command line, continue improving your skills by learning how to pass arguments to your scripts.

Make Sure Your Terminal or Command Prompt Can Run Python

To start, you need to make sure the command line application you are using has access to your Python installation. To do this, open the command prompt, type python and press ‘Enter’. You should see a message that documents the Python version that is being used followed by >>> , which indicates the next code you type will be executed by the Python interpreter. It will look something like this.

Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 Type "help", "copyright", "credits" or "license" for more information. >>>

If you don’t see something similar, it means that you don’t have Python installed or that the command prompt is not aware of your Python installation.

Create a Python Script

Let’s create a very simple script to demonstrate how this works. This Python script (hello.py) will simply print out a statement that lets us know the code in the script has run, as shown below.

print("Hello from my Python script")

Run the Python Script from the Terminal

Once your Python script is created it’s super easy to run it from the terminal or command line. All you need to do is type python followed by the script name. You’ll need to make sure that your terminal’s working directory is the directory that contains your python script, or give the full path to the script. For example. If I just type python hello.py I get the following error.

python: can't open file 'hello.py': [Errno 2] No such file or directory

There are two ways to fix this.

First, specify the full file path. Like this.

C:\Users\Konrad>python c:/konrad/code/python/z_testing/hello.py Hello from my Python script

You can see that by specifying the full path to the python script that the terminal now knows where to find the file to run and I get the proper output.

Читайте также:  Java javascript python работа

Second, use cd to change the terminal’s current directory. Then run the script. Like this.

(base) C:\Users\Konrad>cd c:/konrad/code/python/z_testing (base) c:\konrad\code\python\z_testing>python hello.py Hello from my Python script

By using cd to change the terminal’s directory I no longer need to type the full path to the python script. This is especially useful if you have a number of different scripts in the same directory that you will want to run.

There’s More!

This article gives you a brief, simple introduction to running python scripts from the terminal (or command line). This is a powerful skill to have and there is so much more you can do with it. With a more advanced script, you can pass in parameters/arguments from the command line, which makes it easy to generalize and share your scripts for others to use in various situations. You can check out my guide for passing variables to python scripts from the terminal in this article.

Whether you’re looking to take your GIS skills to the next level, or just getting started with GIS, we have a course for you! We’re constantly creating and curating more courses to help you improve your geospatial skills.

QGIS for Beginners

Remote Sensing with QGIS

QGIS Python Scripting with PyQGIS

All of our courses are taught by industry professionals and include step-by-step video instruction so you don’t get lost in YouTube videos and blog posts, downloadable data so you can reproduce everything the instructor does, and code you can copy so you can avoid repetitive typing

My Recommended Equipment

This article contains affiliate links. When you click on links in this article Open Source Options may make a commission on any sales. This does not have any impact on the price you pay for products.

Video

Konrad has a Master’s Degree in Ecology and a Doctorate Degree in Water Resources and has been performing geospatial analysis and writing code (in multiple programming languages) for over a decade. He writes code to develop models and analysis workflows to predict and evaluate changes to landscapes and water resources. He has published multiple articles in prominent peer-reviewed, scientific journals. Konrad’s code and workflow contribute to operational products that inform water and ecosystem management.

Latest Tutorials

With QGIS reprojections can be calculated with the export data tool, the reproject layer tool, and GDAL Warp. Reprojecting layers (i.e., converting them to a different coordinate reference system, or.

In cartography and GIS, it is to display two different products side by side to make comparisons. This is a powerful and often necessary feature of any serious GIS software. QGIS makes it possible to.

Читайте также:  Css column min height

About Us

We believe data processing and analytics routines should be repeatable without purchasing expensive software licenses. This is possible with open-source programs and programming languages. Our goal is to help you learn open-source software and programming languages for GIS and data science. We do this with free tutorials and paid courses.

Источник

How to Run a Python File in Terminal? (Step-by-Step)

How to Run a Python File in Terminal? (Step-by-Step)

Python is widely used for various purposes, from writing websites’ backends to machine learning algorithms. Some use IDEs like Pycharm to code in Python, some use Visual Studio Code’s extension, and some just use the terminal. Each way of running the Python code is perfectly acceptable but everyone should understand how to run python files in the terminal.

Why run a Python file in a terminal?

A terminal or command-line interface is a text-based interface through which one can perform commands using the operating system’s shell. MacOS and Linux operating systems have Terminals and Windows has Command Prompt.

Running python code through the terminal is the simplest and the most fundamental way one can run programs. Learning how to do that will allow them to understand how the process actually works. Not just that, this knowledge is essential for automation. Automating tasks and scripts requires a good understanding of the terminal.

Terminals can also be used in cases of debugging. Some IDEs do not show the full error output and that could lead to a lot of confusion about where the code is going wrong. Running the same code in a terminal, you can read the entire error and understand the error message to make changes to the code, essentially debugging the code.

Running python files in the terminal also provides more flexibility and control compared to using an IDE, because you can easily modify the arguments passed to the script and execute it from anywhere.

Let us now look at how to do that.

How to run a Python file in a terminal?

Before we get into the step-by-step process, let us first ensure that python is accessible through the terminal. This can be done by just opening the terminal, as explained later in Step 1, and entering the command ‘python’. That should open an interactive python environment that looks something like this:

Python 3.9.12 (main, Apr 5 2022, 06:56:58) [GCC 7.5.0] :: Anaconda, Inc. on linux Type "help", "copyright", "credits" or "license" for more information. >>>

If this does not happen, that means python is not installed properly. Try reinstalling Python. To exit the interactive python environment, enter the following command or function:

Читайте также:  Python send http get request

Running a python file in a terminal is a straightforward and simple process. The following step-by-step guide should help you run go through it:

  1. Open the terminal: In Windows, it’s called Command Prompt. You can open Command Prompt by searching it in the start menu or by searching ‘cmd’ instead. Powershell technically has the same exact functionality too. On macOS or Linux, you can open the terminal by searching “Terminal” in Spotlight or in the applications menu.
  2. Navigate to Directory: Once the terminal or the command prompt is open, the next step is to navigate to the directory of the python file. You can do that with the command ‘cd’ followed by the file directory. If the path of the file directory is “C:/User/Documents/PythonPrograms”, you can enter cd C:/User/Documents/PythonPrograms.
  3. Run File in Folder: Now you have to run the python file in the folder. That can be done with the python command or the python3 command depending on the version of python you are using. The python or python3 command followed by the full file name with the file extension will run the python file in the terminal. For example, enter ‘python main.py’ or ‘python3 main.py’ in the terminal.
  4. Pass Arguments: If your python script requires arguments, the arguments can be passed after the ‘python main.py’. For example, if you have to pass two arguments, say arg1 and arg2, then you have to enter the following command, ‘python main.py argument1 arg2’ or ‘python3 main.py arg1 arg2’.

So, you have successfully run your python script through the terminal. With this knowledge, you can now automate your tasks through the terminal. Here’s an example of a script that you can run in a terminal and it will essentially automate a daily task.

Automating a task through the terminal

Take an example of this simple script that opens Gmail every morning at 10:00 AM.

import schedule import webbrowser def open_gmail(): Url = 'https:mail.google.com' webbrowser.open(url) schedule.every().day.at("10:00").do(open_gmail) while True: schedule.run_pending() time.sleep(1)

You can run this in the terminal with the command “python gmail_script.py” and it will run the file until the terminal is closed and the system is shut down.

Also, learn how to schedule scripts with a task scheduler on windows.

Conclusion

With a simple command, we have unlocked a whole new way for python. Running a Python file in a terminal is valuable because it can help you automate tasks but can also help you debug your code and gain more control over executing scripts.

Источник

Оцените статью