Python - Python Misc, os, shutil

Sys, Print, Argparse Path-Related Utils

Posted by Rico's Nerd Cluster on January 3, 2019

sys

  • Check current python version
1
2
3
4
if sys.version_info.major == 3 and sys.version_info.minor == 10:
    print("Python version is 3.10")
else:
    print(f"Python version is not 3.10, it's {sys.version_info.major}.{sys.version_info.minor}")

Numbers

  • Not a number float('nan'). This is often seen in 0/0
    • In numpy, this is np.nan. To check, it’s numpy.isnan()
  • Multiline Printing
1
2
3
4
print(f'''
line 1
line2
''')
  • Print float with 2 decimal digits
1
print(f"{test_acc:.2f}%")

Argparse

  • Adding a required arg:
1
parser.add_argument("--name", "-n", type=str, required=True, help="Name of a bag in rgbd_slam_rico/data")

os Library

  • Absolute Path
1
script_path = os.path.abspath(__file__)
  • Remove a file if it exists:
1
2
if os.path.exists(output_path):
    os.remove(output_path)

shutil

  • remove non-empty directory:
1
shutil.rmtree(DIR)

For-Else Loop

1
2
3
4
5
6
k = 10
for i in range(k):
    print(k)
    break
else:
    print("hello")