473,788 Members | 3,078 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to close all python-opened file identifiers?

Greetings from beautiful Tucson, Arizona.

Question: Is there a way in Python to determine what all file
identifiers have been opened by Python, and to close them all?

Why I ask: I learned Python after cutting my programming teeth on
Matlab, where you get a list of all open file identifiers (that is,
those opened from a particular Matlab session) with "fopen('all ')" and
close them with "fclose('all')" . In my 4 years of experience with
Python, I haven't yet come across an equivalent means of doing this in
Python. I understand that this problem can be prevented by making
sure a "fid.close( )" exists for every "open"; I need this however for
a file-permissions troubleshooting problem.

Extra info on this specific problem: In my program, python (through
subprocess) launched a text editor on a text file, and I can't seem to
save the text file through that editor (I get a "this document is in
use by another application and cannot be accessed" error from the
editor [wordpad on winXp]). The text file in question is modified by
my program prior to its loading into the launched editor. Although I
can't find unmatched "open" and "fid.close( )" statements, I'd like to
implement a check for open file identifiers before launching the
editor.

Thanks very much in advance for your time and any help you can provide.
Jul 26 '08 #1
2 10894
BAnderton <bl************ @gmail.comwrote :
>
Question: Is there a way in Python to determine what all file
identifiers have been opened by Python, and to close them all?
No. You are expected to be able to track this yourself. Python doesn't
open any files that you didn't request.

>Extra info on this specific problem: In my program, python (through
subprocess) launched a text editor on a text file, and I can't seem to
save the text file through that editor (I get a "this document is in
use by another application and cannot be accessed" error from the
editor [wordpad on winXp]). The text file in question is modified by
my program prior to its loading into the launched editor. Although I
can't find unmatched "open" and "fid.close( )" statements, I'd like to
implement a check for open file identifiers before launching the
editor.
If you want to post some code, perhaps we can find something.
--
Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Jul 27 '08 #2
On Jul 26, 2:19*am, BAnderton <blake.ander... @gmail.comwrote :
*Although I
can't find unmatched "open" and "fid.close( )" statements, I'd like to
implement a check for open file identifiers before launching the
editor.
So you need a debug tool to track down the opened files.
How about that:

# assume Python 2.5
from __future__ import with_statement

import __builtin__

orig_file = __builtin__.fil e # you could do the same for open

class ChattyFile(file ):
opened = []
def __init__(self, *args, **kw):
super(ChattyFil e, self).__init__( *args, **kw)
self.opened.app end(self)
print 'opened %s' % self
def close(self):
super(ChattyFil e, self).close()
self.opened.rem ove(self)
print 'closed %s' % self

class ContextManager( object):
def __init__(self):
self.opened = ChattyFile.open ed
def __enter__(self) :
__builtin__.fil e = ChattyFile
def __exit__(self, *exc_info):
__builtin__.fil e = orig_file

chattyfile = ContextManager( )

with chattyfile:
f = file('x.txt', 'w')
f.write('hello' )
f.close()
file('x.txt')

print chattyfile.open ed

gives:

$ python chattyfile.py
opened <open file 'x.txt', mode 'w' at 0x19df0>
closed <closed file 'x.txt', mode 'w' at 0x19df0>
opened <open file 'x.txt', mode 'r' at 0x19e48>
[<open file 'x.txt', mode 'r' at 0x19e48>]

Warning: I did not test this more than you see.
Notice also that overriding the builtins is fine
for debugging purposes (it is perhaps the only good
use case for this feature, together with testing, for mock objects).
You are expected to use it as follows:

from chattyfile import chattyfile
from mylibrary import main

with chattyfile:
main()

and all calls to 'file' will be tracked down.
Since 'open' is basically an alias for 'file'
(they were exactly the same in Python 2.4)
you could also track 'open' in the same way.
If you are using Python 2.4 you can use the same
trick, but in a less clean way, using a try ..finally
instead of the context manager.

Michele Simionato
Jul 27 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1559
by: Guyon Morée | last post by:
recently i've visited SARAH, the academic supercomputer in Amsterdam, Holland. this is next to the CWI, where Guido founded Python.... ....Yeah!...
1
2044
by: Matthew Wilson | last post by:
Hi - I wrote this program: import Tkinter root = Tkinter.Tk() root.title('tkfun is tktastic!') cc = Tkinter.Canvas(root, width=400, height=400, bg="white")
12
2155
by: Stephen Ferg | last post by:
I've just spent several very frustrating hours tracking down a bug in one of my programs. The problem was that I was writing text to a file, and when I was done I coded f.close when I should have been coding f.close()
20
1814
by: Mark Hahn | last post by:
Prothon is pleased to announce another major release of the language, version 0.1.2, build 710 at http://prothon.org. This release adds many new features and demonstrates the level of maturity that Prothon has reached. The next release after this one in approximately a month will be the first release to incorporate the final set of frozen Prothon 1.0 language features and will be the Alpha release. You can see the set of features still...
3
6459
by: Mike Monaghan | last post by:
I'm rather new to python but a long time programmer. I think I've covered my bases so I hope this isn't somthing obvious. I'm running ActiveState PythonWin 2.3.2 (#49, Nov 13 2003, 10:34:54) on win32. I have several processes that are polling a telnet server on a regular basis. I'm using telnetlib for this. When I issue the .close method the connection is not closed (no TCP FIN is sent to the server).
0
1040
by: Mark Sandler | last post by:
Hi, When i create a process using popen and then if i decide that i am not interested in keeping the process pipes anymore, and I forget the correspond variables . Then, if python tries to destroy pipes and get locked on pipe.close(), until the child process terminates... While this seem to follow specifications (close waits until pipes closes on the other end, and destructor calls close()), it seems like a rather weird behaviour to me:...
3
2597
by: Sullivan WxPyQtKinter | last post by:
Hi,there. Sometimes a python CGI script tries to output great quantities of HTML responce or in other cases, it just falls into a dead loop. How could my client close that CGI script running on the server? I tried to use the STOP button in the web browser button, but it does not work. In addition, how could I configure that if a CGI program do not finish its task in 20sec or so, it will be automatically terminated?
0
1053
by: Irmen de Jong | last post by:
I'm having some troubles with closing sockets using Python 2.5b1 Simply closing a client socket (on the server side) doesn't seem to actually shutdown the socket anymore. A connected client simply hangs, while with older Pythons it aborted with a socket close error. Can someone confirm this for me? Or shed some light on it? More info and a test program is available in the following but report:
0
1389
by: Steve Ingram | last post by:
Found out what I'd done, and it wasn't py2exe causug the problem. I wasn't closing the main dialog properly, I was calling Close() instead of Destroy(), so the dialog stayed in memory, basically it was still running. Thanks for your help, steve -----Original Message----- From: Fredrik Lundh
1
2170
by: johnny | last post by:
I am getting following connection error from my python script: conn.close() AttributeError: adodb_mysql instance has no attribute 'close' Here is my relevant code below: def worker(tq): while True: host, e = tq.get()
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10172
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6749
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4069
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.