Python os module – JournalDev

Python os module - JournalDev Анемометр

Что такое модуль os?

Модуль os в Python — это библиотека функций для работы с операционной системой. Методы, включенные в неё позволяют определять тип операционной системы, получать доступ к переменным окружения, управлять директориями и файлами:

  • проверка существования объекта по заданному пути;
  • определение размера в байтах;
  • удаление;
  • переименование и др.

При вызове функций os необходимо учитывать, что некоторые из них могут не поддерживаться текущей ОС.

Чтобы пользоваться методами из os, нужно подключить библиотеку. Для этого в Python используется import os, который необходимо описать в файле до первого обращения к модулю.

Рекомендуется использовать эту инструкцию в начале файла с исходным кодом.

Capturing output

If you want to capture the output, you can pass subprocess.PIPE to the appropriate stderr or stdout:

>>> from subprocess import PIPE
>>> completed_process = run(shlex.split('python --version'), stdout=PIPE, stderr=PIPE)
>>> completed_process.stdout
b'Python 3.8.8n'
>>> completed_process.stderr
b''

And those respective attributes return bytes.

Commonly used functions

1. os.name: This function gives the name of the operating system dependent module imported. The following names have currently been registered: ‘posix’, ‘nt’, ‘os2’, ‘ce’, ‘java’ and ‘riscos’.

Output:

posix

Note: It may give different output on different interpreters, such as ‘posix’ when you run the code here.

2. os.error: All functions in this module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. os.error is an alias for built-in OSError exception.

Output: 

Problem reading: GFG.txt

 3. os.popen(): This method opens a pipe to or from command. The return value can be read or written depending on whether the mode is ‘r’ or ‘w’. Syntax: 

 os.popen(command[, mode[, bufsize]])

Parameters mode & bufsize are not necessary parameters, if not provided, default ‘r’ is taken for mode. 

Output: 

Hello

Note: Output for popen() will not be shown, there would be direct changes into the file.

4. os.close(): Close file descriptor fd. A file opened using open(), can be closed by close()only. But file opened through os.popen(), can be closed with close() or os.close(). If we try closing a file opened with open(), using os.close(), Python would throw TypeError.

Output: 

Expanded signature

Here’s an expanded signature, as given in the documentation:

Full signature

Here’s the actual signature in the source and as shown by help(run):

def run(*popenargs, input=None, timeout=None, check=False, **kwargs):

The popenargs and kwargs are given to the Popen constructor. input can be a string of bytes (or unicode, if specify encoding or universal_newlines=True) that will be piped to the subprocess’s stdin.

The documentation describes timeout= and check=True better than I could:

Handling the current working directory

Consider Current Working Directory(CWD) as a folder, where the Python is operating. Whenever the files are called only by their name, Python assumes that it starts in the CWD which means that name-only reference will be successful only if the file is in the Python’s CWD.

Note: The folder where the Python script is running is known as the Current Directory. This is not the path where the Python script is located.Getting the Current working directoryTo get the location of the current working directory os.getcwd() is used.

Example:

Output:

Current working directory: /home/nikhil/Desktop/gfg

Changing the Current working directory

To change the current working directory(CWD) os.chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.

Note: The current working directory is the folder in which the Python script is operating.

Example:

Output:

Import os.path vs import os

os.path works strangely actually. It looks like os packaged with a submodule path but actually, os is a normal module which operate with sys.module to support os.path. Let us list what happens behind the scenes:

  • When Python starts, it loads many modules into sys.module.
  • os module is also loaded when Python starts. It assigns its path to the os specific module attribute.
  • It injects sys.modules['os.path'] = path so that you’re able to do import os.path as though it was a submodule.

Is self a keyword?

self is used in so many places in Python that people think it’s a keyword. But unlike this in C , self is not a keyword.

We can actually use any name for the first parameter of a method, but it is strongly advised to stick to the convention of calling it self.

This means that the last class can be made as:


class Person:

    #name made in constructor
    def __init__(another, n):
        another.name = n;

    def get_person_name(another):
        return another.name

See how I used another this time? It works exactly the same way as self.

Listing out files and directories with python

os.listdir() method in Python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then the list of files and directories in the current working directory will be returned.

Про анемометры:  Как получить обычный металл bns? Обыкновенная сталь где найти

Example:

Output:

Files and directories in ' / ' :
['sys', 'run', 'tmp', 'boot', 'mnt', 'dev', 'proc', 'var', 'bin', 'lib64', 'usr', 
'lib', 'srv', 'home', 'etc', 'opt', 'sbin', 'media']

Os.environ

environ is not a function but a process parameter through which we can access environment variables of the system.Let’s see sample code snippet:


import os
output = os.environ['HOME']
print(output)

When we run this script, the following will be the output:
python os environment variable

We can use it to work with the environment variables, read more at Python set environment variable.

Os.error

Python os module error class is the base class for I/O related errors. So we can catch IO errors using OSError in the except clause.


import os

try:
    f = open('abc.txt', 'r')  # file is missing
except OSError:
    print('Error')

Os.execvp

execvp function is one of the ways to run other commands on the system.Let’s see sample code snippet for this function:


import os
program = "python"
arguments = ["hello.py"]
print(os.execvp(program, (program,)    tuple(arguments)))

For this, we just created a sample script as hello.py with following code:


print('Hello')

When we run this script, the following will be the output:
python os module, python os execute other script

Os.getpid

This function returns current process ID or PID, as it is populary known.


>>> os.getpid()
71622

Os.system

Python os system function allows us to run a command in the Python script, just like if I was running it in my shell. For example:

Os.uname

This function return information which identifies current Operating System on which this is executed.


>>> os.uname()
posix.uname_result(sysname='Darwin', nodename='Shubham.local', release='17.2.0', version='Darwin Kernel Version 17.2.0: Fri Sep 29 18:27:05 PDT 2022; root:xnu-4570.20.62~3/RELEASE_X86_64', machine='x86_64')

That was prettry detailed actually.

Pass a command list

One might easily move from manually providing a command string (like the question suggests) to providing a string built programmatically. Don’t build strings programmatically. This is a potential security issue. It’s better to assume you don’t trust the input.

>>> import textwrap
>>> args = ['python', textwrap.__file__]
>>> cp = run(args, stdout=subprocess.PIPE)
>>> cp.stdout
b'Hello there.n  This is indented.n'

Note, only args should be passed positionally.

Popen

When use Popen instead? I would struggle to find use-case based on the arguments alone. Direct usage of Popen would, however, give you access to its methods, including poll, ‘send_signal’, ‘terminate’, and ‘wait’.

Here’s the Popen signature as given in the source. I think this is the most precise encapsulation of the information (as opposed to help(Popen)):

Python class self constructor

Python self can also be used to refer to a variable field within the class:


class Person:

    # name made in constructor
    def __init__(self, n):
        self.name = n

    def get_person_name(self):
        return self.name

In above snippet, self refers to the name variable of the entire Person class. Note that if we have a variable within a method, self will not work. That variable is simply existent only while that method is running and hence, is local to that method.

Python import os

Please note that first of all we have to import OS module in our program, then only we can execute any of it’s functions.

Python import sys

Let us start our journey with these functions and what information they offer. Please note that before running any functions, we need to import it using below command.


import sys

Python multithreading

In this post, we saw some functions in the threading module in Python and how it provides convenient methods to control Threads in a multithreaded environment.

Reference: API Doc

Python sys.argv

This function collects the String arguments passed to the python script. Let’s execute this on the system by making a script:


import sys
print('The command line arguments are:')
for i in sys.argv:
    print(i)

Run this script on terminal now:
python sys.argv, python sys module

This String just displays the copyright information on currently installed Python version. Let’s execute this on the system by making a script:


import sys
print(sys.copyright)

Run this script on terminal now:
python sys copyright

Python sys.exit

This method makes the Python interpretor exits the current flow of execution abruptly. Let’s execute this on the system by making a script:


import sys
print("JournalDev")
sys.exit(1)
print("Hello")

Run this script on terminal now:
python sys exit

Python sys.getrefcount

This python sys module method returns the count for references to an object where it is used. Python keeps track of this value, as, when this value reaches 0 in a program, the memory for this variable is cleaned up. Let’s execute this on the system by making a script:


import sys

variable = "JournalDev"

print(sys.getrefcount(0))
print(sys.getrefcount(variable))
print(sys.getrefcount(None))

Run this script on terminal now:
python sys getrefcount

In this lesson, we learned about various functions provided by sys module in Python and saw how they work. See more lessons on Python here.

Reference: API Doc

Python sys.modules

This function gives the names of the existing python modules current shell has imported. Let’s execute this on the system:


>>> sys.modules.keys()
dict_keys(['builtins', 'sys', '_frozen_importlib', '_imp'])

I have removed many modules as initially Python imports many modules by default. So the output may differ when you will execute this command in your python setup.

Python sys.path

This function just displays the PYTHONPATH set in current system. Let’s execute this on the system by making a script:


import sys
print('nnThe PYTHONPATH is', sys.path, '.n')

Run this script on terminal now:
python sys.path command, python sys functions

Python sys.stdin

This function is used to take . Let’s execute this on the system by making a script:

Python threading

Let us introduce python threading module with a nice and simple example:


import time
from threading import Thread

def sleepMe(i):
    print("Thread %i going to sleep for 5 seconds." % i)
    time.sleep(5)
    print("Thread %i is awake now." % i)

for i in range(10):
    th = Thread(target=sleepMe, args=(i, ))
    th.start()

When we run this script, the following will be the output:
Python Threading Example, Python multithreading example

When you run this program, the output might be different as parallel threads doesn’t have any defined order of their life.

Python threading functions

We will reuse the last simple program we wrote with threading module and build up the program to show different threading functions.

Should we pass self to a method?

Above explanation opens a new question, should we just pass self to a method? Let’s consider the class Person which contains a method something defined as:


def something(another, arg1, arg2):
    pass

If personMe is an instance of the class and personMe.something(arg1, arg2) is called, python internally converts it for us as:


Person.something(personMe, arg1, arg2)

The self variable refers to the object itself.

Про анемометры:  Работоспособность вентиляции | Полезная информация | Управляющая компания МегаЛинк

That’s all for python self and it’s usage in constructor and functions to get the current object reference.

Summary

In this lesson, we read about various functions provided by OS module in Python and saw how they work. See more lessons on Python here.

Reference: API Doc

Threading.active_count()

This function returns the number of threads currently in execution. Let us modify the last script’s sleepMe(…) function. Our new script will look like:


import time
import threading
from threading import Thread

def sleepMe(i):
    print("Thread %i going to sleep for 5 seconds." % i)
    time.sleep(5)
    print("Thread %i is awake now." % i)

for i in range(10):
    th = Thread(target=sleepMe, args=(i, ))
    th.start()
    print("Current Thread count: %i." % threading.active_count())

This time, we will have a new output showing how many threads are active. Here is the output:
Python multithreading example, python threading active count

Note that active thread count, after all 10 threads has started is not 10 but 11. This is because it also counts the main thread inside from other 10 threads were spawned.

Threading.current_thread()

This function returns the current thread in execution. Using this method, we can perform particular actions with the obtained thread. Let us modify our script to use this method now:


import time
import threading
from threading import Thread

def sleepMe(i):
    print("Thread %s going to sleep for 5 seconds." % threading.current_thread())
    time.sleep(5)
    print("Thread %s is awake now.n" % threading.current_thread())

#Creating only four threads for now
for i in range(4):
    th = Thread(target=sleepMe, args=(i, ))
    th.start()

The output of the above script will be:
Python Threading Current Thread

Threading.enumerate()

This function returns a list of all active threads. It is easy to use. Let us write a script to put it in use:


import threading
for thread in threading.enumerate():
    print("Thread name is %s." % thread.getName())

Now, let’s run this script:
Python Threading Enumerate

We were having only Main thread when we executed this script, hence the output.

Threading.main_thread()

This function returns the main thread of this program. More threads can be spawned form this thread. Let us see this script:


import threading
print(threading.main_thread())

Now, let’s run this script:
Python Main Thread

As shown in the image, it is worth noticing that the main_thread() function was only introduced in Python 3. So take care that you use this function only when using Python 3 versions.

Threading.timer()

This function of threading module is used to create a new Thread and letting it know that it should only start after a specified time. Once it starts, it should call the specified function. Let’s study it with an example:


import threading

def delayed():
    print("I am printed after 5 seconds!")

thread = threading.Timer(3, delayed)
thread.start()

Now, let’s run this script:
Python Threading Timer

Using os.makedirs()

os.makedirs() method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing, os.makedirs() method will create them all.

Example: 

Output:

Directory 'Nikhil' created
Directory 'c' created

Using os.mkdir()

os.mkdir() method in Python is used to create a directory named path with the specified numeric mode. This method raises FileExistsError if the directory to be created already exists.

Example: 

Output:

Directory 'GeeksforGeeks' created
Directory 'Geeks' created

Using os.rmdir()

os.rmdir() method in Python is used to remove or delete an empty directory. OSError will be raised if the specified path is not an empty directory.

Example: Suppose the directories are 

Output:

What is a thread?

In Computer Science, threads are defined as the smallest unit of work which is scheduled to be done by an Operating System.

Some points to consider about Threads are:

  • Threads exists inside a process.
  • Multiple threads can exist in a single process.
  • Threads in same process share the state and memory of the parent process.

This was just a quick overview of Threads in general. This post will mainly focus on the threading module in Python.

Вычисление размера

Чтобы определить размер документа или папки, стоит воспользоваться функцией getsize, как это показано в следующем примере для файла test.txt. Функция print выводит размер данного документа в байтах. Воспользоваться getsize можно и для измерения объема директорий.

import os
print(os.path.getsize("D:\test.txt"))

136226

Запуск на исполнение

Встроенные функции библиотеки os позволяют запускать отдельные файлы и папки прямиком из программы. С этой задачей прекрасно справляется метод startfile, которому стоит передать адрес необходимо объекта. Программное обеспечение, используемое для открытия документа, определяется средой автоматически.

import os
os.startfile(r"D:test.txt")

Изменение рабочей директории

По умолчанию рабочей директорией программы является каталог, где содержится документ с ее исходным кодом. Благодаря этому, можно не указывать абсолютный путь к файлу, если тот находится именно в этой папке. Получить сведения о текущей директории позволяет функция getcwd, которая возвращает полный адрес рабочего каталога на жестком диске.

Информация о файлах и директориях

Вывести на экран или в любое другое место основные сведения об объекте можно через метод stat. Поместив ему в качестве параметра расположение файла или папки на диске компьютера, стоит ожидать небольшой массив информации. Здесь можно найти данные о размере объекта в байтах, а также некие числовые значения, отображающие доступ и режим его работы.

import os
print(os.stat(r"D:test.txt"))

os.stat_result(st_mode=33206, …)

Обработка путей

Возвращаясь к классу path из библиотеки os, стоит принять во внимание функцию split, позволяющую очень легко разъединять путь к файлу и имя файла в различные строки. Это демонстрируется на следующем примере с текстовым документом test.txt в папке folder.

import os
print(os.path.split(r"D:foldertest.txt"))

('D:\folder', 'test.txt')

Обратное действие выполняет функция join, позволяя легко соединить путь к документу с его названием. Как видно из результатов работы данного кода, благодаря print на экране будет отображаться путь, который ссылается на текстовый файл test.txt в каталоге folder на D.

import os
print(os.path.join(r"D:folder", "test.txt"))

D:foldertest.txt

Это были базовые возможности модуля os, реализуемые в программах на языке Python за счет множества встроенных методов по управлению установленной ОС. Таким образом, они дают возможность не только получать полезные сведения о платформе, но и работать с содержимым диска, создавая новые директории и файлы, переименовывая и полностью удаляя их.

Про анемометры:  Принцип работы инфракрасного газоанализатора

Переименование

Библиотека os предоставляет возможность быстрой смены названия для любого файла или же каталога при помощи метода rename. Данная функция принимает сразу два разных аргумента. Первый отвечает за путь к старому наименованию документа, в то время как второй отвечает за его новое название.

import os
os.rename(r"D:folder", r"D:catalog")

Переименовывать можно не только один каталог, но и несколько папок сразу, только если все они находятся в одной иерархической цепочке. Для этого достаточно вызвать метод renames и передать ему путь к конечной директории в качестве первого аргумента. В роли же второго параметра выступает аналогичный адрес к папке, но только с новыми именами всей цепочки.

import os
os.renames(r"D:folderfirstsecond", r"D:catalogonetwo")

Получение имени файла и директории

Иногда для взаимодействия с документом необходимо получить его полное имя, включающее разрешение, но не абсолютный путь к нему на диске. Преобразовать адрес объекта в название позволяет функция basename, которая содержится в подмодуле path из библиотеки os. Таким образом, следующий пример показывает преобразование пути test.txt в простое имя файла.

import os
print(os.path.basename("D:/test.txt"))

test.txt

Обратная ситуация возникает тогда, когда пользователю нужно получить только путь к файлу, без самого названия объекта. Это поможет сделать метод dirname, который возвращает путь к заданному документу в строковом представлении, как это продемонстрировано в небольшом примере ниже. Здесь print выводит на экран адрес текстового документа в папке folder.

import os
print(os.path.dirname("D:/folder/test.txt"))

D:/folder

Получение информации об ос

Чтобы узнать имя текущей ОС, достаточно воспользоваться методом name. В зависимости от установленной платформы, он вернет ее короткое наименование в строковом представлении. Следующая программа была запущена на ПК с ОС Windows 10, поэтому результатом работы функции name является строка nt. Увидеть это можно при помощи обычного метода print.

import os
print(os.name)

nt

Получить сведения, которые касаются конфигурации компьютера, можно при помощи метода environ. Вызвав его через обращение к библиотеке os, пользователь получает большой словарь с переменными окружения, который выводится в консоль или строковую переменную.

Проверка существования пути

Чтобы избежать ошибок, связанных с отсутствием определенного файла или директории, которые должны быть обработаны программой, следует предварительно проверять их наличие с помощью метода exists. Передав ему в качестве аргумента путь к нужному файлу или папке, можно рассчитывать на лаконичный ответ в виде булевого значения true/false, сообщающего о наличии/отсутствии указанного объекта в памяти компьютера. В следующем примере идет проверка текстового файла test.txt из корневого каталога D, которая возвращает True.

import os
print(os.path.exists("D:/test.txt"))

True

Если объект на диске реально существует, это не всегда значит, что он имеет подходящую для дальнейшей обработки форму. Проверить, является ли определенный объект файлом, поможет функция isfile, которая принимает его адрес. Ознакомиться с результатом его работы можно из следующего примера, где print отображает на экране значение True для файла test.txt.

import os
print(os.path.isfile("D:/test.txt"))

True

Аналогичные действия можно выполнить и для проверки объекта на принадлежность к классу директорий, вызвав для его адреса метод isdir из библиотеки os. Как можно заметить, в данном случае print выводит на экран булево значение False, поскольку test.txt не является папкой.

import os
print(os.path.isdir("D:/test.txt"))

False

Содержимое директорий

Проверить наличие в каталоге определенных объектов позволяет функция listdir. С её помощью можно получить информацию о файлах и папках в виде списка. В программе немного ниже показано, как метод принимает в качестве параметра путь к каталогу folder на диске D, а затем выводит название внутренней папки first и документа test.txt, вывод в консоль осуществляется с помощью print.

import os
print(os.listdir(r"D:folder"))

['first', 'test.txt']

Воспользовавшись методом walk, можно получить доступ к названиям и путям всех подпапок и файлов, относящихся к заданному каталогу. Применив один внешний цикл for, а также два вложенных, несложно получить информацию об объектах в каталоге folder через специальные списки directories и files. Сведения выдаются с помощью многократного обращения к print.

import os
for root, directories, files in os.walk(r"D:folder"):
    print(root)
    for directory in directories:
        print(directory)
    for file in files:
        print(file)

D:folder
first
D:folderfirst
second
D:folderfirstsecond
third
D:folderfirstsecondthird
test.txt

Создание директорий

Возможности модуля os позволяют не только отображать информацию об уже существующих в памяти объектах, но и генерировать абсолютно новые. Например, с помощью метода mkdir довольно легко создать папку, просто указав для нее желаемый путь. В следующем примере в корневом каталоге диска D производится новая папка под названием folder через mkdir.

import os
os.mkdir(r"D:folder")

Однако на этом возможности по генерации директорий не заканчиваются. Благодаря функции makedirs можно создавать сразу несколько новых папок в неограниченном количестве, если предыдущая директория является родительской для следующей. Таким образом, в следующем примере показывается генерация целой цепочки папок из folder, first, second и third.

import os
os.makedirs(r"D:folderfirstsecondthird")

Удаление файлов и директорий

Избавиться от ненужного в дальнейшей работе файла можно с помощью метода remove, отдав ему в качестве аргумента абсолютный либо относительный путь к объекту. В небольшом коде ниже демонстрируется удаление документа test.txt из корневой директории диска D на ПК.

import os
os.remove(r"D:test.txt")

Чтобы стереть из памяти папку, следует воспользоваться встроенной функцией rmdir, указав ей адрес объекта. Однако здесь присутствуют определенные нюансы, поскольку программа не позволит беспрепятственно удалить директорию, в которой хранятся другие объекты.

import os
os.rmdir(r"D:folder")

Для быстрого удаления множества пустых папок следует вызывать функцию removedirs. Она предоставляет возможность избавиться сразу от нескольких каталогов на диске, при условии, что все они вложены друг в друга. Таким образом, указав путь к конечной папке, можно легко удалить все родительские директории, но только если они в результате оказываются пустыми. В примере показано мгновенное удаление четырех разных папок: folder, first, second, third.

import os
os.removedirs(r"D:folderfirstsecondthird")

Функции модуля os

Методы из библиотеки os могут применяться пользователем для разных целей. Ниже показаны наиболее популярные из них, позволяющие получать данные о операционной системе. Также получать сведения о файлах и папках, хранимых в памяти на жестком диске ПК.

Оцените статью
Анемометры
Добавить комментарий