Linux создать скрипт python

Writing your first Script

Before we write anything, let’s create a folder to hold your Python scripts.

Usually you would choose a hierarchy that’s sensible for you (for example I use Documents/programming/python in my home directory as the root for all of my Python projects!).

For the purposes of this workshop, let’s use your Desktop folder in your U drive and create a folder called

*nix users

Similar to above, but place the python_workshop folder in your home folder (e.g. /home/ubuntu for openstack users).

NB

It’s a slightly confusing convention, but a user’s home folder is the path /home/username , not simply /home .

What is a Python Script?

A Python script is just a plain text file, and the convention is to use the extension .py (instead of e.g. .txt ) to let programs know that it holds Python code.

Python code is very close to something called pseudo-code, which is what people use when detailing the main components of an algorithm.

For example, the pseudo-code for the factorial function (e.g. 3! = 3 x 2 x 1) is

SET fact to n WHILE n is more than 1 SET fact to fact times (n - 1) SET n to n - 1 
fact = n while n > 1: fact = fact * (n-1) n = n - 1 

What this simple example illustrates, is that Python is extremely readable; it just takes becoming familiar with a few base syntax rules (~grammar).

We’ll be speaking Python in no time!

Worked Exercise : Hello, world!

We’ll start by creating a blank Python script file.

Creating a file

We’re going to name our first script file exercise_hello_world.py and keep it inside the newly created python_workshop folder.

To do this, open Notepad++ . You should see a blank file (that may be named “new 1”, or “new 2” etc, depending on if you closed any tabs!).

Starting Notepad++

If you don’t see a blank file, select File->New from the menu bar.

Then select File->Save As , navigate to the python_workshop folder we created a few minutes ago, and set the file name to exercise_hello_world.py and click Save.

Now that we have a blank Python script file, lets start adding some code!

Initial content

 # Author: Your Name # This is a script to test that Python is working 

replacing the text in the line starting # Author with your details.

Running the script with Python: The Terminal

Now let’s see what running this through Python does!

Start a customized command prompt (reminder: in the Windows File Explorer, find the WinPython3 folder on the C: drive, and click on WinPython Command Prompt.exe).

A terminal window should pop up, that looks a little bit like

Reminder: Basic terminal usage

You were advised to have basic knowledge of using a terminal (Windows Command Prompt/Linux Terminal/MacOS Terminal), you are about to see out why!

Here’s a recap of the things you’re most likely to need.

Windows MacOS / Linux What it does
`cd FOLDER_NAME` `cd FOLDER_NAME` Change directory to FOLDER_NAME
`dir FOLDER_NAME` `ls FOLDER_NAME` List folder contents; if FOLDER_NAME
is omitted, list current folder contents
`..` `..` Reference to parent folder. E.g. `cd ..`
is how you would navigate from `/a/b/c/` to
`/a/b/` if you are currently in `/a/b/c/`.
`mkdir FOLDER_NAME` `mkdir FOLDER_NAME` Create a folder called FOLDER_NAME

Quick note on terminology

Folder and directory refer to the same thing, while full path or absolute path means the full directory location. E.g. if you’re currently in your Desktop folder, the folder is Desktop, but the full path is something like /users/joe/Desktop . If you’re on Windows the path starts with a drive letter too, like “C:” or “U:”, and the forward-slashes will be backslashes instead.

Console and terminal (and sometimes shell) are usually used interchangeably to mean the same thing; the text-based interface where commands can be entered. In windows, the built-in console is also called the “command prompt” and is started using cmd.exe .

For our purposes, we’re going to be mainly interested in the terminal console which is where we type commands like cd , or dir .

For interactive Python snippet testing we can also use the Interactive Python console, which is where we can directly type python commands. You might encounter this later; for now just be aware that there are these two types of console.

Now using the terminal command to change directory, cd , navigate to your Desktop directory.

You can verify that it contains your new python_workshop folder by using the windows terminal command dir :

Источник

Linux создать скрипт python

Для создания программ на Python нам потребуется интерпретатор. Стоит отметить, что в некоторых дистрибутивах Linux (например, в Ubuntu) Python может быть установлен по умолчанию. Для проверки версии Python в терминале надо выполнить следующую команду

Версия интерпретатора Python в Linux

Если Python установлен, то она отобразит версию интерпретатора.

Однако даже если Python установлен, его версия может быть не самой последней. Для установки последней доступной версии Python выполним следующую команду:

sudo apt-get update && sudo apt-get install python3

Если надо установить не последнюю доступную, а какую-то определенную версию, то указывается также подверсия Python. Например, установка версии Python 3.10:

sudo apt-get install python3.10

Соответственно, установка версии Python 3.11:

sudo apt-get install python3.11

Запуск интерпретатора

После установки интерпретатора, как было описано в прошлой теме, мы можем начать создавать приложения на Python. Итак, создадим первую простенькую программу. Для этого введем в терминале

В результате запускается интерпретатор Python. Введем в него следующую строку:

И консоль выведет строку «hello METANIT.COM»:

Первая программа на Python в Linux

Для этой программы использовалась функция print() , которая выводит некоторую строку на консоль.

Создание файла программы

В реальности, как правило, программы определяются во внешних файлах-скриптах и затем передаются интерпретатору на выполнение. Поэтому создадим файл программы. Для этого определим для скриптов папку python . А в этой папке создадим новый текстовый файл, который назовем hello.py . По умолчанию файлы с кодом на языке Python, как правило, имеют расширение py .

Создание скрипта на языке Python на Linux

Откроем этот файл в любом текстовом редакторе и добавим в него следующий код:

name = input("Введите имя: ") print("Привет,", name)

Python в Visual Studio Code

Скрипт состоит из двух строк. Первая строка с помощью функции input() ожидает ввода пользователем своего имени. Введенное имя затем попадает в переменную name .

Вторая строка с помощью функции print() выводит приветствие вместе с введенным именем.

Теперь запустим терминал и с помощью команды cd перейдем к папке, где находится файл с исходным кодом hello.py (например, в моем случае это папка metanit/python в каталоге текущего пользователя). И затем выполним код в hello.py с помощью следующей команды

В итоге программа выведет приглашение к вводу имени, а затем приветствие.

Источник

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.

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.

Источник

Читайте также:  Linux start script on login
Оцените статью
Adblock
detector