Linux

Python operating system interfaces

In this chapter we will study, how to interact with OS using Python command. In order to intract with OS, we will have to import OS Module.

Python os.name

The name of the operating system dependent module imported. Its syntax is very simple just import OS module and type os.name.
Python OS.name API
Showing API

You can see Windows OS is showing nt and Linux shows posix The following names have currently been registered: 'posix', 'nt', 'os2', 'ce', 'java', 'riscos'.

os.environ

This command give variety of information. It return a dictionary of information let us see the output.
Python os.environ give Environment variable
mapping object representing the string environment
Let us check some interesting out-put of os.environ.
Python os.environ give Environment variable
mapping object representing the string environment
We are using os.environ['OS'] os.environ['PATH'], os.environ['USERNAME'] but these keys may not be same for the Linux environment.

os.getcwd()

If you want to know your current working directory means from where program is running, use os.getcwd().

os.chdir()

If you want to change your current working directory, use os.chdir().
Python os.getcwd(),os.chdir()
mapping object representing the string environment
Click to view code

os.access()

In simple words os.access is used to check if a user is authorized to open a file before actually doing.
Syntax
os.access(path, mode)

path : path means file or directory with its path.
mode : mode means read write and execute. There are 4 types of modes.
  1. os.F_OK Value to pass as the mode parameter of access() to test the existence of path.
  2. os.R_OK Value to include in the mode parameter of access() to test the readability of path.
  3. os.W_OK Value to include in the mode parameter of access() to test the writability of path.
  4. os.X_OK Value to include in the mode parameter of access() to determine if path can be executed.
Let's discuss with example to understand.
Python os.getcwd(),os.chdir()
Showing access.os and access
Click to view code
The upper code showing 2 runs of a program. First run , when file has all permissions and second run, when file has only read permission.

os.open()

According to Python docs Open the file file and set various flags according to flags and possibly its mode according to mode.
Syntax
os.open(file, flags[, mode])

file : file or directory with its path.
flag : flags are :
  • os.O_RDONLY : open for read only
  • os.O_WRONLY: open for write only
  • os.O_RDWR : open for read and write only
  • os.O_APPEND: open for append
  • os.O_CREAT : create a file if does not exists
This is all similar to Python file operations.
One common mistake mostly done by new users. Always use forward slash / for defining the path.


os.fchdir(fd)

Change the current working directory to the directory represented by the file descriptor fd. The descriptor must refer to an opened directory, not an open file. fd is created by os.open(). This function is only available for unix.
Let's discuss the example
Python os.fchdir(fd), os.open(file, flags[, mode])
Showing access.os and access
Click to view code

os.read()

Read at most n bytes from file descriptor fd. Return a string containing the bytes read. If the end of the file referred to by fd has been reached, an empty string is returned.
Syntax
os.read(fd, n)
fd
: fd is file descriptor create by os.open().
n : Read at most n bytes from file descriptor fd. Let's discuss the example
Python  os.open(file, flags[, mode]), os.read()
Showing os.read()
Click to view code

os.write()

Syntax
os.write(fd, str)

Write the string str to file descriptor fd. Return the number of bytes actually written.
Python  os.open(file, flags[, mode]), os.write(fd, str)
Showing os.write()
Click to view code

os.walk()

This method is used to generate the list of directory and files in top-down or bottom up manner. Syntax
os.walk(top, topdown=True, onerror=None, followlinks=False)

top is top directory given by user , The top contains root, sub-directories and files, here root is top most directory given by user, sub-directories are the directories contained by the root, files are the files contained in root directory and its sub directories.

if topdown=True it means directory search starts from top directory then goes to next directory in another words top to down manner.
if topdown=False it means directory search starts from last directory then goes to top directory in another words bottom to up manner.

onerror -- This can show error to continue with the walk, or raise the exception to abort the walk.
followlinks -- Search follows symlinks, pointed by symlinks, if set to true.
Before discuss the example let's see the directory structure.
Python os.walk()
Showing Directory structure
The F:/Projects/pic is the top directory. The New, old and opty are the sub-directories. Rest all are the files.
Let's discuss example (topdown= False) means bottom-up
Python os.walk(top, topdown=False onerror=None, followlinks=False)
Showing os.walk() in topdown=False
Click to view code
The opty directory is the bottom directory start from the bottom directory then goes to the F:/Projects/pic .
Let's discuss example (topdown= True) means Top-down.
Python os.walk(top, topdown=True onerror=None, followlinks=False)
Showing os.walk() in topdown=True
Click to view code
The F:/Projects/pic directory is the top directory start from the top directory then goes to the opty .

os.popen()

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

os.popen(command) that takes a DOS command is passed in as a string and returns a file-like object connected to the command's standard input or output streams.
mode This is the Mode can be 'r'(default) or 'w'.
The optional bufsize argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size (in bytes). A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used. Let us discuss the example.
 os.popen(command[, mode[, bufsize]])
Showing os.popen() in ping command
Click to view code

os.system()

To execute shell or DOS commands Syntax
os.system("command")
Let us discuss the ping command which run infinite in Windows system.
 os.system(
Showing os.system("command") in ping command
You can see the command ping command is running,

you might be wonder what is the difference between os.popen() and os.system()
Let us discuss next example.
 os.popen() and os.system()
Showing difference bwtween os.popen()and os.system()
Click to view code
Click to view code
You can see that, os.system() just run the command, and os.psopen() can read the output of command.

Consider you want to make program which will run on Windows as well as on Linux. May be both OS offer different commands for same task. like directory creation Linux uses "mkdir" and Windows OS uses "md" command. In this situation you can use "platform" module.
Syntax
platform.system()

Lets see output on different OS.
 platform.system()
platform.system()
After knowing OS you can use if-else statements to run commands.





admin