WorldViz User Forum

WorldViz User Forum (https://forum.worldviz.com/index.php)
-   Vizard (https://forum.worldviz.com/forumdisplay.php?f=17)
-   -   Closing file handles from within function (https://forum.worldviz.com/showthread.php?t=68)

FlyingWren 10-01-2003 05:10 PM

Closing file handles from within function
 
Closing file handles works fine if I don't do it from within a function call.

Consider the following, though. I press a key, and the "file should be closed now" line appears. But, the file doesn't seem to close-- it can't be renamed or deleted without first exiting the program that created it (ie, Vizard).

am I missing something?

Code:


import viz
viz.go()

fileOutput = open(hi.txt', 'a')
fileOutput.write('hi there\n')

def mykeyboardfunc(key):
        fileOutput.flush()
        fileOutput.close()
        print "file should be closed now"
       
viz.callback(viz.KEYBOARD_EVENT, mykeyboardfunc)


farshizzo 10-01-2003 06:02 PM

Hi,

This problem stems from the fact that Vizard runs each script twice. When you first run a script, Vizard parses the script once to check for errors. During this first parse only code in the global scope is executed, code inside functions is not executed. Next, Vizard passes the script off to the graphics engine which parses the script and begins executing code inside functions such as keyboard handlers and timer handlers. What's happening in your case is that the following code is being called twice since it resides in the global scope:
Code:

fileOutput = open(hi.txt', 'a')
fileOutput.write('hi there\n')

However the code to close the file is being called once, so there is still a handle to the file that is left open, which stops you from renaming or deleting it.

Whew, hope that made at least some sense ;)

For now you could do something like the following, but we'll try to come up with a better solution:
Code:

import viz
viz.go()

def mykeyboardfunc(key):
        global fileOutput
        if key == 'o':
                fileOutput = open('hi.txt', 'a')
                fileOutput.write('hi there\n')
               
        if key == 'c':
                fileOutput.flush()
                fileOutput.close()
                print "file should be closed now"

       
viz.callback(viz.KEYBOARD_EVENT, mykeyboardfunc)



All times are GMT -7. The time now is 06:20 AM.

Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Copyright 2002-2023 WorldViz LLC