[TOC]
- Title: Python and Os Utils 2024
- 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:
|
|
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
:
|
|
You can run this script from the command line, providing four arguments separated by spaces like this:
|
|
Using argparse
:
|
|
With the argparse
method, you can run the script similarly:
|
|
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
.