with
statement PTC-W0010with
statement to open a file408
409 elif action == "start":
410 if exists(pidfile):
411 pf = open(pidfile, 'r')412 try:
413 pid = int(pf.read().strip())
414 pf.close()
with
statement to open a file381 if not exists(pidfile):
382 print("%s (instance %s) is not running" % (program, instance))
383 raise SystemExit(1)
384 pf = open(pidfile, "r")385 try:
386 pid = int(pf.read().strip())
387 pf.close()
with
statement to open a file350 if not exists(pidfile):
351 print("Pidfile %s does not exist" % pidfile)
352 raise SystemExit(0)
353 pf = open(pidfile, 'r')354 try:
355 pid = int(pf.read().strip())
356 pf.close()
with
statement to open a file32 For more details, "man proc" and "man uptime"
33 """
34 if platform.system() == "Linux":
35 return open('/proc/loadavg').read().split()[:3]36 else:
37 command = "uptime"
38 process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
with
statement to open a file30 For more details, "man proc" and "man uptime"
31 """
32 if platform.system() == "Linux":
33 return open('/proc/loadavg').read().split()[:3]34 else:
35 command = "uptime"
36 process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
Opening a file using with
statement is preferred as function open
implements the context manager protocol that releases the resource when it is outside of the with
block. Not doing so requires you to manually release the resource.
f = open('/tmp/.deepsource.toml', 'w')
f.write("config file.")
# No `f.close()` statement: file may remain unaccessible
with open('/tmp/.deepsource.toml', 'w') as f:
f.write("config file.")