[TOC]

  1. Title: Python and Os Utils 2024
  2. Review Date: Thu, Jan 18, 2024

Useful Programming Tips

What does " 2>&1 " mean?

To combine stderr and stdout into the stdout stream, we append this to a command:

1
2>&1

Answer

File descriptor 1 is the standard output (stdout).

File descriptor 2 is the standard error (stderr).

At first, 2>1 may look like a good way to redirect stderr to stdout. However, it will actually be interpreted as “redirect stderr to a file named 1”.

& indicates that what follows and precedes is a file descriptor, and not a filename. Thus, we use 2>&1. Consider >& to be a redirect merger operator.

argparse

https://www.youtube.com/watch?v=88pl8TuuKz0

Sure, I can provide you with an example of both sys.argv and argparse methods to read 4 arguments in a Python script.

Using sys.argv:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import sys

if len(sys.argv) != 5:
    print("Usage: python script.py arg1 arg2 arg3 arg4")
else:
    arg1 = sys.argv[1]
    arg2 = sys.argv[2]
    arg3 = sys.argv[3]
    arg4 = sys.argv[4]

    print(f"Argument 1: {arg1}")
    print(f"Argument 2: {arg2}")
    print(f"Argument 3: {arg3}")
    print(f"Argument 4: {arg4}")

You can run this script from the command line, providing four arguments separated by spaces like this:

1
python script.py arg1 arg2 arg3 arg4

Using argparse:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import argparse

def main():
    parser = argparse.ArgumentParser(description="A script that reads 4 arguments.")
    parser.add_argument("arg1", help="First argument")
    parser.add_argument("arg2", help="Second argument")
    parser.add_argument("arg3", help="Third argument")
    parser.add_argument("arg4", help="Fourth argument")

    args = parser.parse_args()

    print(f"Argument 1: {args.arg1}")
    print(f"Argument 2: {args.arg2}")
    print(f"Argument 3: {args.arg3}")
    print(f"Argument 4: {args.arg4}")

if __name__ == "__main__":
    main()

With the argparse method, you can run the script similarly:

1
python script.py arg1 arg2 arg3 arg4

The argparse method provides more flexibility and user-friendly help messages if you want to provide additional information about each argument and handles various argument types and options more gracefully than sys.argv.