Tuesday, 7 June 2022

How does one detect if one is running within a docker container within Python?

 import os, re


path = "/proc/self/cgroup"

def is_docker():
  if not os.path.isfile(path): return False
  with open(path) as f:
    for line in f:
      if re.match("\d+:[\w=]+:/docker(-[ce]e)?/\w+", line):
        return True
    return False

print(is_docker())


from: https://stackoverflow.com/questions/43878953/how-does-one-detect-if-one-is-running-within-a-docker-container-within-python

How does one detect if one is running within a docker container within Python?

  import os, re path = "/proc/self/cgroup" def is_docker (): if not os.path.isfile(path): return False with open (pa...