The sys module

The sys module (https://docs.python.org/3/library/sys.html) allows interacting with the Python run-time interpreter. One of the functions of the sys module is parsing command-line arguments provided as inputs to the program. Let's write a program that reads and prints the contents of the file that is passed as an argument to the program:

import sys
if __name__ == "__main__":
with open(sys.argv[1], 'r') as read_file:
print(read_file.read())

Try running the preceding example as follows:

python3 sys_example.py read_lines.txt

The preceding example is available for download along with this chapter as sys_example.py. The list of command-line arguments passed while running the program are available as a argv list in the sys module. argv[0] is usually the name of the Python program and argv[1] is usually the first argument passed to the function.

When sys_example.py is executed with read_lines.txt as an argument, the program should print the contents of the text file:

I am learning Python Programming using the Raspberry Pi Zero.
This is the second line.
Line 3.
Line 4.
Line 5.
Line 6.
Line 7.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.120.109