'str' object has no attribute 'close with popen.python
'str' object has no attribute 'close with popen.python
I am using the command os.popen
in python and when I try to close it I get the error:
os.popen
'str' object has no attribute 'close
how can I fix this?
I tried reading it repeatedly in another line but this still didn't work.
this is the code lines:
p = os.popen(command, "r").read()
f_temp_command = open("%s/%s%s" % (LOG_DIR, file, LOG_EXT), "w")
f_temp_command.writelines([l for l in p.splitlines()])
p.close()
2 Answers
2
This
p = os.popen(command, "r").read()
binds p
to the result of .read()
, not to the result of os.popen()
. You want:
p
.read()
os.popen()
p = os.popen(command, "r")
r = p.read()
do_something_with(r)
p.close()
or better:
with os.popen(command, "r") as p:
r = p.read()
# no need to close p anymore, it's already done
As a side note, you don't need the list expression here:
f_temp_command.writelines([l for l in r.splitlines()])
since r.splitlines()
already returns a list, so you could replace it with:
r.splitlines()
f_temp_command.writelines(r.splitlines())
or even with:
f_temp_command.write(r)
thanks. it did solve this but now i get the error: f_temp_command.writelines([l for l in p.splitlines()]) File "C:Usersefrat.shpilmanAppDataLocalProgramsPythonPython36libos.py", line 1009, in getattr return getattr(self._stream, name) AttributeError: '_io.TextIOWrapper' object has no attribute 'splitlines'. probably because i didnt close the file yet. is there a way through it?
– Adamso
Jul 2 at 9:45
@Adamso you can't indeed call
splitlines()
on a file object - you want to use the variable bound to the result of p.read()
(r
in my example) instead, obviously.– bruno desthuilliers
Jul 2 at 9:57
splitlines()
p.read()
r
You can not close it bacause read
method return str
object. Use an intermediate variable to store the result.
read
str
p = os.popen(command, "r")
res = p.read()
f_temp_command = open("%s/%s%s" % (LOG_DIR, file, LOG_EXT), "w")
f_temp_command.writelines([l for l in res.splitlines()])
p.close()
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
subprocess.popen is preferred over os.popen
– hd1
Jul 2 at 9:39