How does the python sys module work and what is it for?

Asked

Viewed 4,009 times

2

I am following a book, and I am not able to understand a part about Command line parameters, on this page he is using the sys module and working with the arqv list:

import sys 

print(f"Número de parâmetros: {len(sys.argv)}")
for n, p in enumerate(sys.argv):
    print(f"Parâmetro {n} = {p}")

It uses this method in several following exercises and basically you need to learn how to use sys, just with this explanation above;

BOOK: Introduction to Programming with Python 3rd Edition - 2019 = Pag. 198

  • It is for many things, basically it is a lib with several functions focused mainly to work with the "settings" obtained in the current execution of a script, for example, take parameters, pick environment variables, pick up script path or where it is running from, outside that provides some control in the command line interface, which may vary by interface type or terminal. There must be exact technical "words" in this book, but in general it is this.

  • Could you explain to me how the program that I enclosed in the question works, I could not understand, or some place that I can understand more about the sys module.

  • Your doubt is only about the sys.argv or it’s also about the Python language and how for? Because it seems to me that you have no familiarity with language (maybe), then the explanation can go further.

3 answers

5


The module sys provides functions and variables used to manipulate different parts of the Python runtime environment and although they are completely different, many people confuse the module sys and the module os (module to manipulate the operating system).

With the module sys you can for example, know which device platform is running your code, get the system paths that the Python interpreter uses, imported modules, Python version, among others.


What is sys.argv ?

The sys.argv is not a method, it is a list that stores the parameters passed in the execution of your Python code, the first element being the path of your code. Example:

// arquivo.py
import sys
print(sys.argv)

Now run this code on your terminal by passing some values, as in the example below:

> arquivo.py param1 param2 param3

The way out of this will be:

['C:\\Users\\username\\Desktop\\exemplo\\arquivo.py','param1','param2','param3']

As we can see above, the sys.argv is very useful because we can configure the program externally or else pass data such as email, password and others into it, even after you have compiled or generated an executable code.

3

The module sys Python contains some variables and functions related to the operation of Python itself in the environment in which it is running.

So actually, everything inside the sys has very different roles - has functions that return the maximum recursion limit of Python - which has only to do with the language (sysgetrecusionlimit()). Has functions that return the accent encoding used by default in text files (sys.getdefaultencoding). Has functions to terminate the program immediately, from where Esti view (sys.exit()) - have variables filled automatically with information about the last exception that happened in the program (sys.exc_info) - In short, a lot of things, mostly advanced use - and the only way to know "what’s it for" is to see the documentation: https://docs.python.org/3/library/sys.html

Already the variable sys.argv is one of the most used and simplest to explain -e, as well as everything else in the sys, is not related to other things in the module.

sys.argv is a list of strings that have the parameters passed on the command line to start your program.

So if your program was started on the terminal with the command:

python meuprograma.py aquelearquivo.txt 2 , the variable sys.argv will be a list of strings ["meuprograma.py", "aquelearquivo.txt", "2"] (note that all elements are always strings, even '2' being numerical). With this, Python allows any simple code to interact with the parameters passed by the command line, in addition to bringing a family name to those who program in C, where these parameters are available for the function main in the form of a pointer vector for strings: char **argv - where, in C, the argument count has to come in a separate parameter - int argc. This count is not required in Python because the arguments already come as a Python list, which "knows" its length.

Finally, another differential of sys is that once Python is started, it is already imported automatically - it is not read separately from the disk. For the Python programmer, this is not noticeable, it has to be imported like any other module - but this is only to make the name "sys" available as a variable that can be used. Internally, if you have only the python.exe in Windows, for example, and no library file, you will still be able to use the module sys.

1

The sys module allows using stdin() and stdout(), as well as stderr(), but more interestingly, we can use sys.argv() . For many, this is a confusing concept, but it is quite simple and very useful when you learn it. The idea of sys.argv is to allow you to pass arguments to Python from the command line.

This capability acts as a bridge to the ability to communicate between Python and other languages, which can communicate again through the shell to interact.

With stdout and stdin, we can pass messages and errors to the command line or just use them for registration purposes.

Allows interaction with the Python system:

exit() - sair do modo interativo do Python!
argv - acesso a linha de comandos
path - acesso ao path do sistema
ps1 - para mudar '>>>' prompt do Python!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.