Skip to content

Commit c9445a4

Browse files
committed
printenv: Add printenv.py
1 parent 507535f commit c9445a4

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/printenv.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#!/usr/bin/python3
2+
3+
import os
4+
import sys
5+
from optparse import OptionParser
6+
7+
8+
def printenv(opts, var_names: list[str]):
9+
endchar = "\0" if opts.null else "\n"
10+
11+
if not var_names:
12+
for name, value in os.environ.items():
13+
print(f"{name}={value}", end=endchar)
14+
return
15+
16+
failed = False
17+
for name in var_names:
18+
if value := os.environ.get(name):
19+
print(f"{name}={value}", end=endchar)
20+
else:
21+
failed = True
22+
23+
if failed:
24+
sys.exit(1)
25+
26+
27+
if __name__ == "__main__":
28+
parser = OptionParser(
29+
usage="Usage: %prog [OPTION] [VARIABLE]...",
30+
description="Print VARIABLE(s) or all environment variables, and their corresponding values.",
31+
add_help_option=False,
32+
)
33+
parser.add_option("--help", action="help", help="show usage information and exit")
34+
35+
parser.add_option("-0", "--null", action="store_true")
36+
37+
printenv(*parser.parse_args())

0 commit comments

Comments
 (0)