How to modify the way the code is being read

68 views
Skip to first unread message

likage

unread,
Sep 18, 2014, 5:55:29 AM9/18/14
to python_in...@googlegroups.com
I am still having some trouble where my UI just closes when it is hitting upon a warning where the UI should still be present for users to go back and change some stuff.

In the following are three functions:
  • chkBox : when enabled, it will also enables the textfield. So if the textfield is blank, it will prompt a warning else it will carry on.
  • readFileIn : the function for the Creation button in my UI, so supposedly if everything is working fine and dandy, it should creates the locator and group it else it will halt any if the obj parse is wrong.
  • ReadObjCloud : parses the information of the obj file. So if the first character is not V, it will prompts and Invalid warning. But this portion seems to be the one giving me the most problem, as while it is able to differentiate whether there are V characters in the first character, the ui closes on me instead of the user going back to the ui and reimport a working obj file...
Even though it seems to be 'working', I have also got the following error in my editor:

#
# Error: Please import in a relevant Point Cloud Obj file
# Traceback (most recent call last):
#   File "/user_data/test/chan.py", line 202, in readFileIn
#     ReadObjCloud(self.finalObjPath)
#   File "//user_data/test/chan.py", line 261, in __init__
#     raise Exception( "Please import in a relevant Point Cloud Obj file\n")
# Exception: Please import in a relevant Point Cloud Obj file #


This is my code, and I think it is happening somewhere in either of the three functions but I am unable to figure it out the hell of me.

class CustomNodeTranslator(OpenMayaMPx.MPxFileTranslator):
   
...
   
...
   
   
def chkBox(self):
        importCloudCheck
= cmds.checkBox(self.cloudCheckbox, query=True, value=True)
        finalObjPath
= cmds.textField(self.waveFileAddress, query=True, text=True)
       
if(importCloudCheck == 1):
           
if finalObjPath != "":
               
ReadObjCloud(finalObjPath)
               
return True
           
else:
               
return False
       
else:
           
print ("Importing in Camera only")
           
return True
   
   
   
def readFileIn(self, *args):
       
if self.chkBox():
            chanRotationOrder
= cmds.optionMenuGrp(self.rotationOrderControl, value=True, query=True)

           
self.importTheChan = ChanFileImporter(chanRotationOrder)
           
           
try:
               
for line in self.fileHandle:
                   
self.processLine(line)
               
self.fileHandle.close()

               
self.closeWindow()
           
           
except:
                sys
.stderr.write( "Failed to read file information\n")
               
raise
       
else:
            cmds
.warning("Input a valid Point Cloud Path or checked off the Import option ")
       


class ReadObjCloud():
   
def __init__(self, objPath):
        fileHandle
= open(objPath,"r")
        filePath
= os.path.basename(fileHandle.name)
        fileName
= os.path.splitext(filePath)[0]

       
print fileHandle.readline()[0]

       
if fileHandle.readline()[0] == "v":
           
for line in fileHandle:
                brokenString
= string.split(line)
                cmds
.spaceLocator(name = "camera1_locator", absolute=True, position=(\
               
float(brokenString[1])*100\
               
, float(brokenString[2])*100\
               
, float(brokenString[3])*100))
                cmds
.CenterPivot()
                cmds
.scale(0.5, 0.5, 0.5)
               
            fileHandle
.close()
               
            cmds
.select("camera1_locator*")
            objGroup
= cmds.group(n=("pointCloud_" + fileName))
            cmds
.xform(os=True, piv=(0, 0, 0))
            cmds
.scale(0.01, 0.01, 0.01)
            cmds
.delete(constructionHistory=True)

            cmds
.select(objGroup, "camera1, add=True)
            cmds.group(n="
cameraTrack")
            cmds.scale(10, 10, 10)
       
        else:
            raise Exception( "
Please import in a relevant Point Cloud Obj file\n")



Justin Israel

unread,
Sep 18, 2014, 7:55:57 AM9/18/14
to python_in...@googlegroups.com

This looks like it should be pretty easy to narrow down, since it is obviously in the ReadObjCloud constructor.

You read one line and print the first character. Is that a throw away line or are you accidentally advancing your file handle past the first line when you didn't meant to? Is the first character of the second line supposed to be "v"? Why not just print the file path you are opening and print the second line to confirm it is what you expect?

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/ab8ff867-ca94-4e61-8a51-6b1722fe350a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Hans Baldzuhn

unread,
Sep 18, 2014, 8:00:22 AM9/18/14
to python_in...@googlegroups.com
Maya is catching you own exception, raised on the final line, 
This line :
fileHandle.readline()[0] == "v"
Evaluates to false so the exception is raised here:
raise Exception( "Please import in a relevant Point Cloud Obj file\n")



likage

unread,
Sep 18, 2014, 10:32:05 PM9/18/14
to python_in...@googlegroups.com
For the obj files, it should be in the following format:
Correct Version (This obj file actually contains the 'vertex' positional values and so the first line always contains this v character then vn... )
v -0.6110637188 0.0093309134 8.1327419281
vn
-0.2112581345 -0.7280599689 -0.6521492792
v
0.7267020941 0.0233836491 8.6937112808
vn
-0.0528684395 -0.1126191291 -0.9922307493





Wrong Version (This is about the same format when exporting of obj.)
# This file uses centimeters as units for non-parametric coordinates.

mtllib aaa
.mtl
g
default
v
-7.768849 -7.768849 7.768849


And the reason that I have coded for it to read and check if the first character is 'v', is to counter the function that was previously written.
Previously, my code for the processLine is something like this:

def __init__(self, objPath):
       
try:

            fileHandle
= open(objPath,"r")
            filePath
= os.path.basename(fileHandle.name)
            fileName
= os.path.splitext(filePath)[0]

               
           
for line in fileHandle:
               
self.processLine(line)
            fileHandle
.close()

               
       
except:
            sys
.stderr.write( "Failed to read file information\n")
           
raise

       
       
# Selects all the imported locators, grouped and transformed it
        cmds
.select(camSel[0] + "_locator*")

        objGroup
= cmds.group(n=("pointCloud_" + fileName))
        cmds
.xform(os=True, piv=(0, 0, 0))
        cmds
.scale(0.01, 0.01, 0.01)
        cmds
.delete(constructionHistory=True)


        cmds
.select(objGroup, camSel[0], add=True)

        cmds
.group(n="cameraTrack")
        cmds
.scale(10, 10, 10)

   
   
def processLine(self, line):
       
if(line[0] == "v"):
            brokenString
= string.split(line)
           
           
# Creation of locators and they are named with the prefix of the imported camera
            cmds
.spaceLocator(name = camSel[0] + "_locator", absolute=True, position=(\

           
float(brokenString[1])*100\
           
, float(brokenString[2])*100\
           
, float(brokenString[3])*100))
            cmds
.CenterPivot()
            cmds
.scale(0.5, 0.5, 0.5)
This has actually caused me some issues, thus I wrote it this way. Maybe it is not a good idea after all?
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.

likage

unread,
Sep 19, 2014, 12:42:41 AM9/19/14
to python_in...@googlegroups.com
I rewrite my code again, will this be any better?
By the way, I am still getting the part where my UI closes itself if it found an invalid file

class ReadObjCloud():
   
""" read in vertex data from nuke 3d camera track """

 
   
def __init__(self, objPath):
       
       
try:
            fileHandle
= open(objPath,"r")

           
self.fileHandle = fileHandle
            filePath
= os.path.basename(fileHandle.name)
            fileName
= os.path.splitext(filePath)[0]
           
           
for char in fileHandle.readline()[0]:
               
if char.startswith("v"):
                   
self.processLine()

                   
                   
# Selects all the imported locators, grouped and transformed it
                    cmds
.select(camSel[0] + "_locator*")
                    objGroup
= cmds.group(n=("pointCloud_" + fileName))
                    cmds
.xform(os=True, piv=(0, 0, 0))
                    cmds
.scale(0.01, 0.01, 0.01)
                    cmds
.delete(constructionHistory=True)

                    cmds
.select(objGroup, camSel[0], add=True)
                    cmds
.group(n="cameraTrack")
                    cmds
.scale(10, 10, 10)

                   
               
else:
                   
self.noProcess()

               
       
except:
            sys
.stderr.write( "Failed to read file information\n")
           
raise

       
   
def processLine(self):
       
       
for line in self.fileHandle:

            brokenString
= string.split(line)
           
           
# Creation of locators and they are named with the prefix of the imported camera
            cmds
.spaceLocator(name = camSel[0] + "_locator", absolute=True, position=(\
           
float(brokenString[1])*100\
           
, float(brokenString[2])*100\
           
, float(brokenString[3])*100))
            cmds
.CenterPivot()
            cmds
.scale(0.5, 0.5, 0.5)

       
       
self.fileHandle.close()
       
   
def noProcess(self):
       
print "INVALID - Re-import again!!!"


Justin Israel

unread,
Sep 19, 2014, 3:35:43 AM9/19/14
to python_in...@googlegroups.com

To be honest,  that rewrite is doing a lot of strange things.

You read the first character of the first line and loop over that single character string to see if it starts with 'v'. At that point you have burned the first line and won't process it. Then your processLine function actually loops over the remaining lines. Is readline() doing what you think it does? It doesn't always start from the beginning. Every time you read, you advance the file handle. You would want to just read one character, and check if it is 'v', and then use seek(0) to move the offset back to the start and read all the lines.

I can't write up an example at the moment, but if you don't figure it out by the time I get to a computer, I will try and post something.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/091119de-fb86-451b-9162-9fe93ef592a7%40googlegroups.com.

likage

unread,
Sep 19, 2014, 3:43:41 AM9/19/14
to python_in...@googlegroups.com
hmm.. okay, bummer for me.

I thought if in my processLine function, having it to read through all the lines in the self.fileHandle would be a different case scenario...
Now I am totally lost...
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.

Justin Israel

unread,
Sep 19, 2014, 3:55:39 AM9/19/14
to python_in...@googlegroups.com

For now, just call self.fileHandle.seek(0) at the start of your processLine function.

To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/64c719fb-6b35-4e36-887b-190ad6c5e47b%40googlegroups.com.

damon shelton

unread,
Sep 19, 2014, 10:38:46 AM9/19/14
to python_in...@googlegroups.com

In your logic you should readline ().strip ()  then split the line by white space and if splits [0] is 'v' then use splits[1]  splits[2] splits[3] as X y z coordinates

On a note. Obj format usually just dumps groups of types together

All v together all vs together all f together mainly because most sections refer to other sections by Id

Justin Israel

unread,
Sep 19, 2014, 5:04:30 PM9/19/14
to python_in...@googlegroups.com
Here is a really quick generic example of parsing that file format:

I didn't use any Maya-specific concepts here because those are easily filled in. The focus of this example was to highlight reading from a file handle, and using seek() to make sure you reset the offset after you have consume some data to validate it. I also broke out the processing of each line into handlers, which makes it pretty easy to read and extend to support more line types. 

Maybe this helps a bit and you could apply some of this to your Maya-specific code?

-- justin



likage

unread,
Sep 23, 2014, 10:50:51 PM9/23/14
to python_in...@googlegroups.com
I am curious, if it is possible for me to simply modify the current code I have, rather than dumping in a whole new bunch of codes? No offence here (just getting frustrated with this code of mine), just thought that if the initial coding is somewhat working, except that I will need to modify the style, then why not..
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsubscribe@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.

Justin Israel

unread,
Sep 23, 2014, 11:22:32 PM9/23/14
to python_in...@googlegroups.com
Like I said, at the very least you want to throw in that filehandle.seek(0) after you read the first line to determine if it contains a 'v'. At least after doing that you can be sure you will be parsing the whole file. 
    for char in fileHandle.readline()[0]:
        if char.startswith("v"
):
            fileHandle.seek(0)
            self.processLine()
I will just cover my eyes and pretend I don't see the part of the code where it does a for-loop over a single character, or the shadowing of python builtins  ;-)


To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/d540641c-fda2-438c-9ace-2d1c75aa540c%40googlegroups.com.

likage

unread,
Sep 23, 2014, 11:36:01 PM9/23/14
to python_in...@googlegroups.com
ok... by the way, correct me if I am wrong, in your code, when I tried it, it does not run pass the __init__ function?
Cause it just seems to stop there and not proceeding to print out the verts information. Am I missing a line somewhere?

Justin Israel

unread,
Sep 23, 2014, 11:39:11 PM9/23/14
to python_in...@googlegroups.com
Not sure if I follow. Are you saying that you expected the constructor of the ObjProcessor class to immediately do all of the parsing work? If so, then the answer is that it is not supposed to do anything. A class constructor shouldn't implicitly have a bunch of side effects or start doing a bunch of work. The usage would be to instantiate the ObjProcessor with a filename, and then call process() on the instance to start the work. 
 

On Wed, Sep 24, 2014 at 3:36 PM, likage <dissid...@gmail.com> wrote:
ok... by the way, correct me if I am wrong, in your code, when I tried it, it does not run pass the __init__ function?
Cause it just seems to stop there and not proceeding to print out the verts information. Am I missing a line somewhere?

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

likage

unread,
Oct 2, 2014, 11:19:30 PM10/2/14
to python_in...@googlegroups.com
I have sort of figure out what is happening in my initial code, seeing that no matter what is done in the ReadObjCloud and it will goes back to the self.closeWindow in the readFileIn, as mentioned by you all...

So what I did is adding in a validation variable by returning True or False and have it set up in the chkBox function before it continues on to readFileIn.
Anyway, thank you all!

Reply all
Reply to author
Forward
0 new messages