- 2. Using Python on Unix platforms¶
- 2.1. Getting and installing the latest version of Python¶
- 2.1.1. On Linux¶
- 2.1.2. On FreeBSD and OpenBSD¶
- 2.1.3. On OpenSolaris¶
- 2.2. Building Python¶
- 2.3. Python-related paths and files¶
- 2.4. Miscellaneous¶
- 2.5. Custom OpenSSL¶
- Python Execute Unix / Linux Command Examples
- os.system example (deprecated)
- Say hello to subprocess
- Related media
- Запуск python скрипта в Linux
- Запуск python скрипта в Linux
- Выполнение команд Linux и Windows в Python
- Введение
- Простой пример
- Простой пример Windows
- Bash команда с опциями
- Передать переменную в аргумент команды
- args, returncode, stdout
- Обработка ошибок
- Передача аргументов в скрипт
- Логи с помощью subprocess
- Сравнить два файла
2. Using Python on Unix platforms¶
2.1. Getting and installing the latest version of Python¶
2.1.1. On Linux¶
Python comes preinstalled on most Linux distributions, and is available as a package on all others. However there are certain features you might want to use that are not available on your distro’s package. You can easily compile the latest version of Python from source.
In the event that Python doesn’t come preinstalled and isn’t in the repositories as well, you can easily make packages for your own distro. Have a look at the following links:
for Debian users
for OpenSuse users
for Fedora users
for Slackware users
2.1.2. On FreeBSD and OpenBSD¶
FreeBSD users, to add the package use:
OpenBSD users, to add the package use:
For example i386 users get the 2.5.1 version of Python using:
2.1.3. On OpenSolaris¶
You can get Python from OpenCSW. Various versions of Python are available and can be installed with e.g. pkgutil -i python27 .
2.2. Building Python¶
If you want to compile CPython yourself, first thing you should do is get the source. You can download either the latest release’s source or just grab a fresh clone. (If you want to contribute patches, you will need a clone.)
The build process consists of the usual commands:
Configuration options and caveats for specific Unix platforms are extensively documented in the README.rst file in the root of the Python source tree.
make install can overwrite or masquerade the python3 binary. make altinstall is therefore recommended instead of make install since it only installs exec_prefix /bin/python version .
2.3. Python-related paths and files¶
These are subject to difference depending on local installation conventions; prefix ( $
For example, on most Linux systems, the default for both is /usr .
Recommended location of the interpreter.
prefix /lib/python version , exec_prefix /lib/python version
Recommended locations of the directories containing the standard modules.
prefix /include/python version , exec_prefix /include/python version
Recommended locations of the directories containing the include files needed for developing Python extensions and embedding the interpreter.
2.4. Miscellaneous¶
To easily use Python scripts on Unix, you need to make them executable, e.g. with
and put an appropriate Shebang line at the top of the script. A good choice is usually
which searches for the Python interpreter in the whole PATH . However, some Unices may not have the env command, so you may need to hardcode /usr/bin/python3 as the interpreter path.
To use shell commands in your Python scripts, look at the subprocess module.
2.5. Custom OpenSSL¶
To use your vendor’s OpenSSL configuration and system trust store, locate the directory with openssl.cnf file or symlink in /etc . On most distribution the file is either in /etc/ssl or /etc/pki/tls . The directory should also contain a cert.pem file and/or a certs directory.
Download, build, and install OpenSSL. Make sure you use install_sw and not install . The install_sw target does not override openssl.cnf .
Build Python with custom OpenSSL (see the configure –with-openssl and –with-openssl-rpath options)
Patch releases of OpenSSL have a backwards compatible ABI. You don’t need to recompile Python to update OpenSSL. It’s sufficient to replace the custom OpenSSL installation with a newer version.
Источник
Python Execute Unix / Linux Command Examples
H ow do I execute standard Unix or Linux shell commands using Python? Is there a command to invoke Unix commands using Python programs?
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Python |
Est. reading time | N/A |
You can execute the command in a subshell using os.system() . This will call the Standard C function system(). This function will return the exit status of the process or command. This method is considered as old and not recommended, but presented here for historical reasons only. The subprocess module is recommended and it provides more powerful facilities for running command and retrieving their results.
os.system example (deprecated)
In this example, execute the date command:
In this example, execute the date command using os.popen() and store its output to the variable called now:
Say hello to subprocess
The os.system has many problems and subprocess is a much better way to executing unix command. The syntax is:
In this example, execute the date command:
You can pass the argument using the following syntax i.e run ls -l /etc/resolv.conf command:
Another example (passing command line args):
In this example, run ping command and display back its output:
The only problem with above code is that output, err = p.communicate() will block next statement till ping is completed i.e. you will not get real time output from the ping command. So you can use the following code to get real time output:
Related media
A quick video demo of above python code:
References:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
307 ms?
That’s a long interval 😉
Hi, please more small and usefull examples with python like it! more code snippets!
A very comprehensive explanation, being useful to beginners to python.
where to find the command of linux
these commands are very helpfull us….please give more example like this.
What exactly does Shell=True does?
please tell the exact usage of the shell argumet.
First off, enjoy all your posts and youtube videos. Recently viewed your tutorial on installing freebsd. So thank you for sharing your knowledge.
I have a query regarding launching an external bash script file (.sh) in freebsd.
For linux I used:
os.system(‘sh ‘ + filepath)
For Mac:
os.system(‘open ‘ + filepath)
And for windows:
os.startfile(filepath)
I am unable to get any of these to work for freebsd. I know startfile is only for windows, however was wondering if there was an equivalent for freebsd without using subprocess. Or if not possible at all how to use subprocess to call a external script.
Also, in freebsd, what would be the equivalent of say:
sudo chown -R user:user file.bundle
as both sudo and chown are not installed by default.
Any help would be appreciated.
What if I want to create a variable in Python, then pass that variable to a bash command line?
Something like this:
….
celsius = sensor.read_temperature()
import subprocess
subprocess.call([“myscript.sh”, “-v”, “-t $celsius”])
Is that possible?
Of course you can. In python’s new formatting it would look like this:
subprocess.call([«myscript.sh», «-v», «-t <>«.format(celsius)])
I use split so I dont have to write literal arrays. Works most of the time.
Источник
Запуск python скрипта в Linux
Python — очень популярный язык программирования для написания различных системных скриптов в Linux. В Windows, там где не хватает возможностей командной оболочки используется PowerShell. В Linux же, когда возможностей Bash не хватает используется язык Python.
На этом языке написано огромное количество системных программ, среди них пакетный менеджер apt, видеоредактор OpenShot, а также множество скриптов, которые вы можете установить с помощью утилиты pip. В этой небольшой статье мы рассмотрим как запустить Python скрипт в Linux с помощью терминала различными способами.
Запуск python скрипта в Linux
Для примера нам понадобится Python скрипт. Чтобы не брать какой-либо из существующих скриптов, давайте напишем свой:
print(«Hello from losst!»)
Для того чтобы запустить скрипт необходимо передать его интерпретатору Python. Для этого просто откройте терминал с помощью сочетания клавиш Ctrl + Alt + T, перейдите в папку со скриптом и выполните:
Если вы хотите, чтобы после выполнения скрипта открылась консоль, в которой можно интерактивно выполнять команды языка Python используйте опцию -i:
python -i script.py
Но как вы могли заметить, при запуске apt или openshot не надо писать слово python. Это намного удобнее. Давайте разберемся как это реализовать. Если вы не хотите указывать интерпретатор в командной строке, его надо указать в самом скрипте. Для этого следует в начало скрипта добавить такую строчку:
Сохраните изменения, а затем сделайте файл скрипта исполняемым с помощью такой команды:
chmod ugo+x script.py
После этого можно запустить скрипт Python просто обращаясь к его файлу:
Если убрать расширение .py и переместить скрипт в каталог, находящийся в переменной PATH, например /usr/bin/, то его можно будет выполнять вот так:
Как видите, запуск команды python Linux выполняется довольно просто и для этого даже есть несколько способов. А каким способом пользуетесь вы? Напишите в комментариях!
Источник
Выполнение команд Linux и Windows в Python
Введение
В этой статье вы узнаете как выполнять команды Linux и Windows из кода на Python 3.
Создайте файл subprocess_lesson.py и копируйте туда код из примеров.
Запустить файл можно командой python3 subprocess.py
Простой пример
Пример программы, которая выполняет Linux команду ls
import subprocess subprocess.run( ‘ls’ )
Простой пример Windows
Пример программы, которая выполняет в Windows команду dir
import subprocess subprocess.run(‘dir’, shell = True )
У меня пока что не работает
Bash команда с опциями
Чтобы выполнить Bash команду с опциями, например, ls — la нужно добавить shell = True
import subprocess subprocess.run( ‘ls -la’ , shell = True )
У использования shell = True есть одна важная особенность: нужно особенно внимательно следить за безопастностью.
Рекомендуется использовать shell = True только если вы передаёте параметры самостоятельно.
Избежать использования shell = True можно передав команду и параметры списком:
import subprocess subprocess.run([ ‘ls’ , ‘-la’ ])
Передать переменную в аргумент команды
По аналогии с предыдущим параграфом — в качестве аргумента можно использовать и переменную
import subprocess text = «Visit TopBicycle.ru to support my website» subprocess.run([ «echo» , text])
Visit TopBicycle.ru to support my website
args, returncode, stdout
Разберём subprocess более подробно
import subprocess p1 = subprocess.run([ ‘ls’ , ‘-la’ ]) print(«p1») print(p1) print(«p1.args») print(p1.args) print(«p1.returncode») print(p1.returncode) print(«p1.stdout») print(p1.stdout)
total 12 drwxrwxr-x 2 andrei andrei 4096 Nov 30 17:57 . drwxrwxr-x 3 andrei andrei 4096 Nov 30 17:57 .. -rw-rw-r— 1 andrei andrei 195 Nov 30 16:51 subprocess_lesson.py p1 CompletedProcess(args= ‘ls -la’ , returncode=0) p1.args ls -la p1.returncode 0 p1.stdout None
Чтобы не выводить результат в терминал а сохранить в переменную, нужно воспользоваться опцией capture_output = True
import subprocess p1 = subprocess.run([ ‘ls’ , ‘-la’ ], capture_output = True ) print(p1.stdout)
b’total 12\ndrwxrwxr-x 2 andrei andrei 4096 Nov 30 18:41 .\ndrwxrwxr-x 3 andrei andrei 4096 Nov 30 18:40 ..\n-rw-rw-r— 1 andrei andrei 92 Nov 30 18:41 subprocess_lesson.py\n’
Если byte вывод вам не нравится его можно декодировать
import subprocess p1 = subprocess.run([ ‘ls’ , ‘-la’ ], capture_output = True ) print(p1.stdout.decode())
total 12 drwxrwxr-x 2 andrei andrei 4096 Nov 30 18:41 . drwxrwxr-x 3 andrei andrei 4096 Nov 30 18:40 .. -rw-rw-r— 1 andrei andrei 101 Nov 30 18:46 subprocess_lesson.py
Или можно использовать опцию text=True
import subprocess p1 = subprocess.run([ ‘ls’ , ‘-la’ ], capture_output = True , text=True) print(p1.stdout)
total 12 drwxrwxr-x 2 andrei andrei 4096 Nov 30 18:41 . drwxrwxr-x 3 andrei andrei 4096 Nov 30 18:40 .. -rw-rw-r— 1 andrei andrei 101 Nov 30 18:46 subprocess_lesson.py
Ещё один вариант перенаправления вывода stdout=subprocess.PIPE
import subprocess p1 = subprocess.run([ ‘ls’ , ‘-la’ ], stdout=subprocess.PIPE, text=True) print(p1.stdout)
total 12 drwxrwxr-x 2 andrei andrei 4096 Nov 30 18:41 . drwxrwxr-x 3 andrei andrei 4096 Nov 30 18:40 .. -rw-rw-r— 1 andrei andrei 101 Nov 30 18:46 subprocess_lesson.py
import subprocess with open(‘output.txt’, ‘w’) as f: p1 = subprocess.run([ ‘ls’ , ‘-la’ ], stdout=f, text=True)
Обработка ошибок
Добавим заведомо неверное условие в команду. Например, пусть листинг выполняется не для текущей директории а для несуществующей.
import subprocess p1 = subprocess.run([ ‘ls’ , ‘-la’ , ‘not_exist’], capture_output = True , text=True) print(p1.returncode) print(p1.stderr)
2 ls: cannot access ‘not_exist’: No such file or directory
Обратите внимане, что Python в этом примере не выдаёт никаких ошибок
Чтобы Python информировал об ошибках во внешних командах используйте опцию check = True
import subprocess p1 = subprocess.run([ ‘ls’ , ‘-la’ , ‘not_exist’], capture_output = True , text=True, check = True ) print(p1.returncode) print(p1.stderr)
Traceback (most recent call last): File «subprocess_lesson.py», line 3, in p1 = subprocess.run([ ‘ls’ , ‘-la’ , ‘not_exist’], capture_output = True , text=True, check = True ) File «/usr/lib/python3.8/subprocess.py», line 512, in run raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command ‘[ ‘ls’ , ‘-la’ , ‘not_exist’]’ returned non-zero exit status 2.
Обратите внимане, что теперь Python выдаёт ошибку, а до print(p1.returncode) и print(p1.stderr) дело уже не доходит
import subprocess p1 = subprocess.run([ ‘ls’ , ‘-la’ , ‘not_exist’], stderr=subprocess.DEVNULL) print(p1.stderr)
Передача аргументов в скрипт
Допустим, нужно вызвать скрипт с несколькими аргументами
import subprocess subprocess.call([‘./script.sh %s %s %s’ %(ip, username, test_time)], shell = True )
Ещё пример: из python скрипта вызвать sed и обрезать число строк, которое сам скрипт получает как аргумент
import subprocess LINES = int(sys.argv[1]) subprocess.call([‘sed -i -e 1,%sd 2021-10-10-log.txt’ %(LINES)], shell = True )
Эту задачу можно решить на чистом Python решение
with open(‘file_with_lines.txt’, ‘r’) as fin: data = fin.readlines()[3:] with open(‘file_with_lines.txt’, ‘w’) as fout: fout.writelines(data)
Логи с помощью subprocess
Если запускать код в какой-то среде, где лог в файл неудобен а лог с помощью print невозможен, можно использовать echo из bash
import subprocess text = «Andrei Log: robot/src/libraries/TestController.py is running» subprocess.run ([ «echo» , text ])
Сравнить два файла
Если запускать код в какой-то среде, где лог в файл неудобен а лог с помощью print невозможен, можно использовать echo из bash
Источник