Запустить python через терминал linux

How to Open and Run Python Files in the Terminal

A Python file or script is written in the Python language and saved with a «.py» extension. In this article, we focus on how to interact with Python files. We will learn how to create and open Python files in the terminal. We will also demonstrate how to run Python files in the terminal and redirect the output of the script to a file.

A Python file may contain a few up to several thousand lines of code that perform one or more tasks. For instance, we may have a Python file that reads data files from different locations, performs some manipulation on them, and writes the resulting data file to another location.

However, how to write Python code or scripts is a separate topic. Thankfully, Python is an easy-to-learn language that is popular for its simplicity.

LearnPython.com takes it one step further and makes the Python learning experience smooth and efficient. It offers several well-organized courses and tracks. Furthermore, the interactive console of LearnPython.com allows for practicing, a must in learning a programming language.

If you are new to Python, start learning with Python Basics. Part 1. By completing this course, you learn concepts such as variables, lists, conditional statements, loops, and functions, which are fundamental topics for programming and software development.

Let’s go back to our main topic of working with Python files in the terminal. We will use the text editor Vim to create a Python file. Vim comes pre-installed on macOS, but there are many different alternatives to choose from such as Sublime and Atom.

How to Create Python Files in the Terminal

Let’s start with opening a terminal and creating a project directory. Then, we change the working directory to the project folder using the «cd» command.

open python files in terminal

We create a Python file by typing «vim» along with the file name. My Python file is called «today.py.» You may name yours anything you’d like. Make sure it ends with the extension «.py».

open python files in terminal

After typing this command, hit enter. Vim opens up the following screen:

open python files in terminal

This is an empty Python file. To modify it, we need to hit «i», the command for switching to the insert or edit mode. When you hit «i», you see the following screen, and you can insert text into the file.

open python files in terminal

This Python file performs a very simple task. As its name suggests, it prints today’s date when executed. There are many different ways of doing this simple task; here, we use the built-in datetime module of Python.

open python files in terminal

In this first line, we import the datetime module. Modules and libraries make development processes easier because we can import and use their functionalities right away. Python also has numerous third-party libraries created by an active open-source community. Here is a list of top Python libraries if you’d like to discover more.

The today method of the datetime module returns a timestamp that contains the current date and time. Since we only need the date, we may also use the date method. The str constructor converts the date object to a string. Finally, we print today’s date using an f-string.

Читайте также:  Probe function in linux

Our script is complete now. To exit the edit mode, hit ESC. Do not close the terminal yet because the file has not been saved. The command to save the file and close the editor is «:wq». The «w» is for «write», meaning we are writing to the file «today.py». The «q» is for «quit».

open python files in terminal

Once you type the «:wq» command, hit enter. The editor closes, and you see the following screen.

open python files in terminal

The file «today.py» has been saved in the «project-1» directory.

How to Open Python Files in the Terminal

We can view the content of existing files with a text editor. Let’s see an example using the file we just created.

The command «vim today.py» opens this Python file in the terminal. This command is the same as the one used for creating the file. Since the text editor knows the file exists, it opens the file instead of creating a new one.

Type the command «vim today.py» in the terminal and hit enter. Any other text editor, such as Sublime and Atom, works similarly. Then, you see the following screen:

open python files in terminal

How to Run Python Files in the Terminal

We have learned how to create Python files and how to open Python files in the terminal to view their contents. How about executing the file to see what it does? We can run Python files in the terminal as well.

First, we need to make sure the current working directory is the one in which the file is located. We open a terminal and change the directory to «project-1» since the «today.py» file was saved in that directory.

The command to execute a Python file is «python» or «python3» depending on how Python is installed on your computer. We type that along with the name of the file to be executed.

open python files in terminal

As we see in the output above, our script prints today’s date in the terminal.

Python scripts may be executed with arguments. Let’s write another script that gives us the date that is n number of days from today. The value of n is determined using a command-line argument.

Let’s name this script «from_today.py».

open python files in terminal

The next step is to open the Python file in the terminal using the command «vim from_today.py» and write the script that performs the task. To use command-line arguments, we need the sys module.

open python files in terminal

Once you write the Python code above in the file «from_today.py», exit the edit mode and save it.

We can now execute the file. Let’s ask the script to find the date 10 days from now:

open python files in terminal

Great! We have managed to execute a Python script with a command-line argument.

In the examples we have seen so far, the output of the file is displayed in the terminal. Let’s say we also want to write the output of this script to another file. Every time it is executed, the output is recorded in a text file. This is a very useful practice for keeping logs.

We can create a text file using Vim as follows:

  1. Open a terminal window and change the directory to «project-1» using the command «cd project-1».
  2. Type «vim logs.txt» and hit enter.
  3. The Vim editor opens a file. Press «i» and then hit ESC.
  4. Finally, type «:wq» to save the file in the directory «project-1».

In our Python Basics. Part 2 course, you learn much more about how to work with text files. In addition, this course covers two fundamental data structures in Python: lists and dictionaries.

Читайте также:  Virtualbox linux windows образ

The next step is to modify the «today.py» file so that it writes its output to the «logs.txt» file when it is executed. In the same terminal window, we open the file «today.py» by typing «vim today.py» and hitting «Enter». After the file is opened, hit «i» to switch to the edit mode and modify the script as shown below:

open python files in terminal

The last two lines open the «logs.txt» file and then write the value of the variable today in it. The «\n» is for writing a new line, so every output is in a separate line. I have also made a small change in the second line. The output is a datetime now instead of just the date. After making these changes, hit ESC and then type «:wq» to save them.

To learn more about date and time in Python, take our Python Basics. Part 3 course. It also covers two other important data structures in Python: sets and tuples.

We are not done yet! Always test your code. I execute the file «today.py» a couple of times.

open python files in terminalI then check the content of the file «logs.txt» to see if the output has been written there. Let’s open the file now by typing the command «vim logs.txt». open python files in terminal

As we see in the screenshot above, the output has been written in the «logs.txt» file as well.

Create, Open, and Run Python Files in the Terminal

We have seen how to create, open, and run Python files in the terminal. The «today.py» file we created is essentially a Python program, even though it is just 5 lines of code. It imports a built-in Python module to create a date object, then prints the value of the object in the console and writes it to another file. Learn more about how to work with files and directories in Python in this article.

What we have done in this article is only a very small part of what you can do with Python. It is one of the most popular programming languages and is used in a variety of areas, such as data science, web development, and mobile game development. Python is a great choice for a career in one of these fields.

Start with the Learn Programming with Python track. It introduces you to the fundamentals of programming. You do not need to have any prior experience with IT. This track consists of 5 fully interactive Python courses, carefully organized and presented for beginners.

There is a high demand for people with Python skills. Once you get comfortable with Python, there will be lots of jobs waiting for you!

Источник

How to Run Python Scripts in Linux

Python is one of the most popular programming languages of all. It’s an interpreted, object-oriented, high-level programming language that features dynamic semantics. If you’re using Linux, then you’ll come across Python scripts quite frequently.

One of the most basic and crucial things to learn is running a Python script when learning or working with Python. Because Python is an interpreted language, it requires the Python interpreter to execute any Python code. Depending on the type of script, there are a couple of ways you can execute it.

This guide will showcase executing a sample Python script.

Python scripts

Any script is a text file containing the code. The file can then be run using an interpreter. The same goes for any Python script.

Читайте также:  На чем основан alt linux

Generally, a Python script will have the file extension PY. However, there’s another way of writing a Python script: embedding Python codes into a bash script.

Either way, you need to have the Python package installed in your system. Because it’s a popular programming language, all Linux distros offer pre-built Python binaries directly from the official package servers. Distros like Ubuntu, Linux Mint, Pop! OS etc., comes with Python pre-installed. The package name should be “python” or “python3″ for any other distros”.

Working with a Python script

Creating a sample Python script

For demonstration, let’s make a quick Python script. Open up the terminal and create a file named sample-script.py.

To be able to run the script, it must be marked as an executable file. Mark the file as an executable.

Check the file permission to verify if it worked.

Writing a sample Python code

Now, we’re going to put some code in the script. Open up the file in any text editor. For demonstration, I’m going to be using the nano text editor.

We’ll place a simple program that prints “hello world” on the console screen.

Save the file and close the editor.

Running the Python script

Finally, we can run the script. Call the Python interpreter and pass the location of the file.

Bash-style Python script

So far, we’ve seen the default way of running a Python script. However, there’s an unconventional way of writing and running a Python script as a shell script.

Generally, a shell script contains a list of commands that are interpreted and executed by a shell (bash, zsh, fish shell, etc.). A typical shell script uses shebang to declare the desired interpreter for the script.

We can take this structure to our advantage. We’ll declare the Python interpreter as the desired interpreter for our code. The body of the script will contain the desired Python scripts. Any modern shell will execute the script with the Python interpreter.

The structure will look something like this.

Location of Python interpreter

The shebang requires the path of the interpreter. It will tell the shell where to look for the interpreter. Generally, a Python interpreter is available as the command “python” or “python3”. Python 2 is deprecated, so it’s not recommended to use it anymore (except in very specific situations).

To find the location of the Python interpreter, use the which command. It finds the location of the binary of a command.

Creating a shell script

Similar to how we created the Python script, let’s create an empty shell script.

Mark the script as an executable file.

Writing a sample shell script

Open the script file in a text editor.

First, introduce the shebang with the location of the interpreter.

We’ll write a simple Python program that prints “hello world” on the next line.

Save the file and close the editor.

Running the script

Run the script as you’d run a shell script.

Final thought

It needs to be passed on to the interpreter to run a Python code. Using this principle, we can use various types of scripts to run our Python code. This guide demonstrated running Python scripts directly (filename.py scripts) or indirectly (filename.sh).

In Linux, scripts are generally used to automate certain tasks. If the task needs to be repeated regularly, it can also be automated with the help of crontab. Learn more about using crontab to automate various tasks.

About the author

Sidratul Muntaha

Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.

Источник

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