programming languagesPython Programming

System Functions in Python explained with Example codes

System functions in Python

To conclude this Python language overview, in this section we will introduce some basic system functions in python, many of which are located in the module sys. This module must therefore be integrated with import:

import sys


Access to the program parameters

sys.argv contains the list of all parameters that were passed to a Python script. You must ensure that the first list element contains the program name, which you usually do not want to evaluate. Access the remaining elements the easiest way to do this is in Formsys.argv [1:].

Access to standard input and standard output

sys.stdin and sys.stdout contain file objects that you use to output data to the standard output or to read data from the standard input. The same functions are available to you as for ordinary files. It is best to send error and logging messages to sys.stderr.

Determine module meta information

sys.path provides the path in which Python searches for modules. You can use the list if necessary, add additional directories and then add modules from these Load directories. sys.modules provides a list of all already loaded modules.



exit program

Usually a Python program ends with the execution of the last statementor when an unhandled error occurs. If you have a program exit early, run sys.exit (). With sys.exit (n) you can also return an error code (see Table 1). Alternatively, you can also pass a character string to the exit method, which is then used as an error message as shown. In this case, 1 is automatically used as the error code.

Table 1: Typical Linux error codes

Error code Importance
0 OK, no mistake
1 General error
2 incorrect parameters (i.e. in argv)
3–127 specific error codes of the program

Note:

exit produces an exception: Note that the exit method internally throws a SystemExit exception. The The end of the program can therefore be prevented with try / except.

Call up other programs or commands

With subprocess.call you can use a Python script to create another program or execute command. In the simplest case, you pass a List with the command name and the associated options:

#! / usr / bin / python3

import subprocess

returncode = subprocess. call (['ls', '-l'])

This executes the command ls. For a Python script that is stored in a Terminal is running, you will see the output of the command there. But you can do not process further in your program. If that’s what you want, use instead of call the check_output method. It provides the output of the commandas a byte string. With decode (‘utf8’) you can turn it into an ordinary Unicode String. The easiest way to process line by line is to use readline:

#! / usr / bin / python3

import subprocess

result = subprocess. check_output (["ls", "-l"])

for line in result. decode ('utf8'). splitlines ():

print (line)




If you want your command to be executed from the standard shell, click the Raspberry Pi from bash, pass the to call or check_output additional parameter shell = True. This has two advantages:

  • On the one hand, you can now save the command or commands to be executed in a specify a simple string, where the pipe character | works so

for example:

result = \

subprocess. check_output ('dmesg | grep -i eth', shell = True)
  • On the other hand, the shell evaluates the wildcards * and? from what you uncomplicated Can process files that match a certain pattern:
result = \

subprocess. check_output ('ls -l *. py', shell = True)

However, using the shell causes a higher overhead. If it If you want to execute many commands as quickly as possible, you should click shell = True if possible dispense.

If an error occurs in the called command or if this has a return value does not equal 0, an exception occurs in the Python program. Because of that you should always secure call and check_output with try / except. Here you can You are using the exception type OSError. With call you should also include the return code evaluate. Numbers less than 0 are considered error codes.

try:

returncode = subprocess. call ("ls", shell = True)

if returncode <0:

print ("error code", return code)

else:

print ("Everything is fine, return code", return code)

except OSError as e:

print ("OSError - Exception", e)


Wait (sleep) system functions in python

On the Raspberry Pi in particular, it is often necessary to use a waiting for a specific event, e.g. on pressing a key. Under no circumstance you should simply formulate a loop here that uninterrupted the state of a GPIO pin. The loop would completely unnecessary the entire CPU resources of the Raspberry Pi. In such cases it is better to use your program put to sleep with time.sleep (n) for the specified time in seconds. n can be a floating point number, so there is the possibility of only a few fractions of a second waiting. The following mini script shows the use of sleep:

#! / usr / bin / python3

import time

for i in range (100):

print (i)

time. sleep (0.2)

 

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button