- Accessing command-line arguments:
```
import sys
if len(sys.argv) > 1:
. print(“The first command-line argument is:”, sys.argv[1])
else:
. print(“No command-line arguments provided.”)
```
In this example, we’re checking if any command-line arguments were passed to the script using `len(sys.argv)`. If there is at least one argument, we’re printing out the first argument using `sys.argv[1]`.
2. Redirecting standard output to a file:
```
import sys
sys.stdout = open(‘output.txt’, ‘w’)
print(“This line will be redirected to output.txt”)
```
In this example, we’re redirecting standard output to a file called “output.txt” using `sys.stdout = open(‘output.txt’, ‘w’)`. Any subsequent print statements will now write to this file instead of printing to the console.
3. Getting the size of an object in memory:
```
import sys
my_list = [1, 2, 3, 4, 5]
print(“The size of my_list is”, sys.getsizeof(my_list), “bytes.”)
```
In this example, we’re using `sys.getsizeof()` to get the size of a Python list object in memory. We’re printing out the size in bytes using `print()`.
4. Adding a directory to the module search path:
```
import sys
sys.path.append(‘/path/to/my/module’)
import my_module
```
In this example, we’re adding a directory to the module search path using `sys.path.append()`. We can now import modules from this directory using the `import` statement.
These are just a few examples of the magic usages of the `sys` library in Python. There are many other functions and parameters available in the library that can be useful for various purposes.