Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
popen and close
#1
Hi,

In a statement obj = os.popen("ls").read()
Should a close statement like obj.close() be called or it is not necessary?

Also for subp = subprocess.Popen(...), should a close statement be called after it?

Thank you.
Reply
#2
You should not use os.popen().
Subprocess Popen or Run is a safer and better version of os.popen().

Usually there is no need to close eg like stdout and stderr pipes.
>>> import subprocess

>>> out = subprocess.run(["ls"], capture_output=True)
>>> out
CompletedProcess(args=['ls'], returncode=0, stdout=b'001.png\n002.png\n003.png\n004.png\n', stderr=b'')

>>> print(out.stdout.decode('utf-8'))
001.png
002.png
003.png
004.png
Reply
#3
Thanks for the response, I know that os.popen is obsoleted, but I just want to know in general to use os.popen or subprocess.popen are safe, won't cause memory leak. So, there is no need to use close for os.popen or subprocess.popen, right?

The only close needs be used is when the open is called.

Thank you.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020