Let's talk about Sys
Tags: python, beginners
Published: 2021-05-24 12:45:41

Everybody loves Python (Trust me, everybody does). But _why_? An __intuitive__, __simple__, yet __highly scalable__ language, Python is a _dynamically typed_, _interpreted language_. However, we will not dive into the nitty-gritty of Python's properties but will instead focus on the functionality of the interpreter of Python.

`sys` module in Python provides information about constants, functions, and methods of the Python interpreter. Moreover, it also provides access to multiple variables under the command of the interpreter and their associated methods. So basically `sys` module allows one to operate over the interpreter, so what, is it useful?

Let's talk about some interesting use cases of `sys` module.

## Installation

But first of all, how to access the `sys` module?

`sys` is part of `Python 3.x` Standard Library, so no separate installation is required.

Just `import` it and you are good to go.

To verify `sys`, let's start by checking its version.

```py
# Imports
import sys

print(sys.version)
```

```text
3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)]
```

Viola! It's working. For more information about sys and its license, run `sys.copyright`.

### Basic Usage

Let's start with some basic use cases of `sys` module.

- `sys.maxsize` returns the max value that an int variable can hold.

```py
import sys

print(sys.maxsize)
```

```
9223372036854775807
```

- `sys.path` returns a list containing all the paths to all the Python Modules and the interpreter in the running environment.

```py
import sys

print(sys.path)
```

```
['C:\\Users\\asus\\PycharmProjects\\Auto_Caption_Generator', 'C:\\Users\\asus\\PycharmProjects\\Auto_Caption_Generator', 'C:\\Program Files\\JetBrains\\PyCharm 2020.3.3\\plugins\\python\\helpers\\pycharm_display', 'C:\\Users\\asus\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip', 'C:\\Users\\asus\\AppData\\Local\\Programs\\Python\\Python38\\DLLs', 'C:\\Users\\asus\\AppData\\Local\\Programs\\Python\\Python38\\lib', 'C:\\Users\\asus\\AppData\\Local\\Programs\\Python\\Python38', 'C:\\Users\\asus\\Music_Classification']
```
- `sys.platform` can be used to identify the running platform (operating system).

```py
import sys

print(sys.platform)
```

```
win32
```

- `sys.executable` tells where the Python interpreter is present.

```py
import sys

print(sys.executable)
```

```
C:\Users\asus\Music_Classification\Scripts\python.exe
```
- `sys.modules` returns a dictionary containing names of all modules in the current environemnt.


```py
import sys

print(sys.modules)
```

```py
{'sys': <module 'sys' (built-in)>, 'builtins': <module 'builtins' (built-in)>, '_frozen_importlib': <module 'importlib._bootstrap' (frozen)>, '_imp': <module '_imp' (built-in)>, '_warnings': <module '_warnings' (built-in)>, '_frozen_importlib_external': <module 'importlib._bootstrap_external' (frozen)>, '_io': <module 'io' (built-in)>, 'marshal': <module 'marshal' (built-in)>, 'nt': <module 'nt' (built-in)>, '_thread': <module '_thread' (built-in)>, '_weakref': <module '_weakref' (built-in)>, 'winreg': <module 'winreg' (built-in)>, 'time': <module 'time' (built-in)>, 'zipimport': <module 'zipimport' (frozen)>, '_codecs': <module '_codecs' (built-in)>, 'codecs': <module 'codecs' from 'C:\\Users\\asus\\AppData\\Local\\Programs\\Python\\Python38\\lib\\codecs.py'>, 'encodings.aliases': <module 'encodings.aliases' from 'C:\\Users\\asus\\AppData\\Local\\Programs\\Python\\Python38\\lib\\encodings\\aliases.py'}
```
- `sys.exit` can be used to terminate a program at once.
- Apart from these CLI usages, sys can be used for I/O as well:
    * __stdin__ (Get input from the command line)
    * __stdout__ (Display output on the screen, the beloved print is just a wrapper around stdout object)
    * __stderr__ (The source of all the error messages, each and 
every exception is handled and written to stderr) 

## Advanced Usecase

These are some simple usage of `sys` module. Let's take one advanced use case:

I made a script to determine the traffic on all of my GitHub Repositories. I was having a look at the Pickled database and was unable to determine the corresponding Repo. I knew that my script took the name of GitHub Repo as an argument. By using `sys.argv` in the driver code. I was able to determine the exact arguments provided to the script.

```py
if __name__ == "__main__":
    main()
    print("Arguments: ", str(sys.argv))
```

```json
2021-05-13T00:00:00Z {"uniques": 1, "count": 4}
2021-05-20T00:00:00Z {"uniques": 1, "count": 2}

2 elements
Arguments:  ['github_traffic.py', 'view', '-u', 'vybhav72954', '-r', 'My_Junk']
```

Granted, there are more straightforward ways to sort this problem, but using `sys.argv` can be really helpful when writing scripts containing multiple classes and functions.

## In Closing

__Sys__ is another helpful module in Python Standard Lib, which has multiple basic to advanced use cases, with standard I/O being the most practical application, `sys` can be used in other scenarios as well, which are discussed above.

There is much more to `sys` but was out of scope for this blog like managing hooks, recursion depth, traces, encoding, and profiles. There are other useful methods as well; for a detailed insight, have a look [here](https://docs.python.org/3/library/sys.html).