+ All Categories
Home > Documents > Python 3 - Bournemouth University · PDF file65...

Python 3 - Bournemouth University · PDF file65...

Date post: 06-Feb-2018
Category:
Upload: phamthien
View: 225 times
Download: 1 times
Share this document with a friend
25
Python 3 Reading and writing Files Monday, 31 January 2011
Transcript
Page 1: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

Python 3Reading and writing Files

Monday, 31 January 2011

Page 2: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

Files• One of the simplest way of communicating between

different packages and different programs is by the use of text files.

• Reading and writing files in python is very simple and allows us to very quickly output elements from one software package to another in an easily readable hence debuggable way.

Monday, 31 January 2011

Page 3: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

File processing : order of

operations

Open File with

open

Get File

Name

File Open? Report Error

Read or write

DATA

FINISHED?

Close File

close

end

No

yes

no

yes

Monday, 31 January 2011

Page 4: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

Stream IO• When a file is opened a file descriptor is

returned and this file descriptor is used for each subsequent I/O operation, when any operation is carried out on the file descriptor its is known as a stream.

• When a stream is opened the stream object created is used for all subsequent file operations not the file name.

Monday, 31 January 2011

Page 5: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

The open function

• The open function takes two parameters

• The fist one is a String for the name of the file to open

• The 2nd one is the open mode “r” for reading from a file “w” for writing to a file

1 # open a file for reading2 FILE=open(FileName,"r")34 # open a file for writing5 FILE=open(FileName,"w")

Monday, 31 January 2011

Page 6: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

The close function

• Once a file has been finished with it must be closed.

• This is especially important if we are writing to a file as the OS may be storing these values in memory.

• The close function actually forces the OS to flush the file to disk and closes thing properly

1 FILE.close()

Monday, 31 January 2011

Page 7: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

1 #!/usr/bin/python23 import os4 import shutil5 import sys67 def Usage() :8 print "ReadFile [filename]"9

10 def main(argv=None):11 # check to see if we have enough arguments12 if len(sys.argv) !=2 :13 Usage()14 else :15 # get the old and new file names16 FileName=sys.argv[1]17 if (os.path.exists(FileName)) :18 FILE=open(FileName,"r")19 lines=FILE.readlines()20 # now we have read the data close the

file21 FILE.close()22 LineNum=023 for line in lines :24 print "%04d %s" %(LineNum,line),25 LineNum+=12627 if __name__ == "__main__":28 sys.exit(main())

Open a file passed on the command line and print the contents

Monday, 31 January 2011

Page 8: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

1 #!/usr/bin/python

23 import os

4 import shutil

5 import sys

6 # import the uniform function from random

7 from random import uniform

89 def Usage() :

10 print "WriteData [filename] Number"

1112 def main(argv=None):

13 # check to see if we have enough arguments

14 if len(sys.argv) !=3 :

15 Usage()

16 else :

17 # get the file name to write to

18 FileName=sys.argv[1]

19 # convert the 2nd argument to an int

20 Num=int(sys.argv[2])

21 # try to open the file

22 try :

23 FILE=open(FileName,"w")

24 # if this fails catch the error and exit

25 except IOError :

26 print "Error opening file",FileName

27 return28 # loop and create some ranom values to write to the file

29 for i in range(0,Num) :

30 FILE.write("Point %f %f %f\n" %(uniform(-10,10),uniform(-10,10),

uniform(-10,10)) )

31 # finally close the file

32 FILE.close()

33 if __name__ == "__main__":

34 sys.exit(main())

Monday, 31 January 2011

Page 9: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

1 Point 8.040192 -0.405584 8.2825152 Point -4.348876 9.117686 3.3076123 Point 0.284490 -8.635971 3.2912734 Point 0.092318 -9.290154 8.6492485 Point 3.125148 -7.677539 -5.2339376 Point 4.029233 -8.312551 -0.4783547 Point 2.601833 8.167995 5.2300838 Point -6.664861 0.562662 2.4418499 Point 5.003445 -3.522960 -3.876358

10 Point -8.750782 -7.294186 1.573799

Monday, 31 January 2011

Page 10: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

Reading the data back

• The following example reads the data from the previous program and prints it out.

• As the data is stored on a per line basis we can read it in one hit and then process it

Monday, 31 January 2011

Page 11: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

1 #!/usr/bin/python

23 import os

4 import shutil

5 import sys

6 # import the uniform function from random

7 from random import uniform

89 def Usage() :

10 print "ReadData [filename] "

1112 def main(argv=None):

13 # check to see if we have enough arguments

14 if len(sys.argv) !=2 :

15 Usage()

16 else :

17 # get the file name to write to

18 FileName=sys.argv[1]

19 # try to open the file

20 try :

21 FILE=open(FileName,"r")

22 # if this fails catch the error and exit

23 except IOError :

24 print "Error opening file",FileName

25 return26 # loop and create some ranom values to write to the file

27 Lines=FILE.readlines()

28 FILE.close()

29 for line in Lines :

30 # lets see if the line is a point

31 if line.startswith("Point") :

32 # now split it and convert it to a numberic value

33 line=line.split()

34 x=float(line[1])

35 y=float(line[2])

36 z=float(line[3])

37 print "%f %f %f" %(x,y,z)

38 if __name__ == "__main__":

39 sys.exit(main())

Monday, 31 January 2011

Page 12: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

A Practical Example

• The following example shows the advantage of all the graphics applications we use having a Python interface

• I use the same code for reading in data and processing it for each package then use application specific code for the actual interface to Maya, Houdini. xsi and renderman

Monday, 31 January 2011

Page 13: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

MedianCut Filter

• The median cut filter program loads an exr image file and partitions it into areas of equal light intensity based on user parameters

• These can then be mapped to lights in a scene to create simple image based lighting elements

Monday, 31 January 2011

Page 14: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

Original Image

mediancut -S -n 200 -i 0.01 -r 4 pisa.exr

Monday, 31 January 2011

Page 15: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

Partition Lightmap

Monday, 31 January 2011

Page 16: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

Monday, 31 January 2011

Page 17: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

Partition Lightmap

• The map output in the program is purely for visual reference.

• At the same time the map is generated a simple text file is also generated in the following format

1 xpos ypos zpos red green blue Shadow Intensity shadowAngle penumbra23 0.832849 3.90942 -0.151102 0.517578 0.255859 0.120117 0 0.01 30 20

Monday, 31 January 2011

Page 18: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

Loading the map1 lightFile=open(fileName,'r')2 # read in all the data3 try :4 data=lightFile.readlines()5 #now read through the file and grab data6 for line in data :7 # tokenise the data into tuple light8 light=line.split()9 # File Line Format is x,y,z r,g,b, Shadowed[1,0], Intensity

10 # we need to use the constructors for float to ensure we get floatsnot strings

11 x=float(light[0])12 y=float(light[1])13 z=float(light[2])14 r=float(light[3])15 g=float(light[4])16 b=float(light[5])17 # we convert shad to a boolean18 shad=bool(light[6])19 intensity=float(light[7])20 # create a name for the light21 LightName=GroupName+"%d" %(LightNum)

Monday, 31 January 2011

Page 19: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

Monday, 31 January 2011

Page 20: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

Houdini Version

Monday, 31 January 2011

Page 21: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

1 import hou23 # main function4 def ReadLightMap(fileName, GroupName,fov):5 # first we get to obj level and create some vars etc6 # first we get the object level78 net = hou.node("/obj")9 # create a networkbox for the lights

10 nb=net.createNetworkBox(GroupName)11 # LightNum used to append to GroupName for the Light12 LightNum=013 # so we open the file for reading14 lightFile=open(fileName,'r')15 # read in all the data16 try :17 data=lightFile.readlines()18 #now read through the file and grab data19 for line in data :20 # tokenise the data into tuple light21 light=line.split()22 # File Line Format is x,y,z r,g,b, Shadowed[1,0], Intensity23 # we need to use the constructors for float to ensure we get floats not strings24 x=float(light[0])25 y=float(light[1])26 z=float(light[2])27 r=float(light[3])28 g=float(light[4])29 b=float(light[5])30 # we convert shad to an int31 shad=int(light[6])32 intensity=float(light[7])33 # create a name for the light34 LightName=GroupName+"%d" %(LightNum)35 # now run houdini commands to create the light dome from map3637 # create a point light and reference it as clight38 # the default light is pointlight so no need to set it39 # may change this as could be changed!40 clight=net.createNode('hlight',LightName)4142 #set the light position43 clight.parm('tx').set(x)44 clight.parm('ty').set(y)45 clight.parm('tz').set(z)464748 # set the light colours49 clight.parm('light_colorr').set(r)50 clight.parm('light_colorg').set(g)51 clight.parm('light_colorb').set(b)52 # set intensity53 clight.parm('light_intensity').set(intensity)54 # set shadow on 0 = none 1= ray trace 3(not implemented but depth map)55 clight.parm('shadow_type').set(shad)56 # set the light fov based on the param passed in57 clight.parm('light_fov').set(fov)58 # parent it to the net box59 nb.addNode(clight)60 LightNum+=1;61 finally :62 # finished with the file so close63 lightFile.close()6465 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15)

Monday, 31 January 2011

Page 22: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

XSI Version

Monday, 31 January 2011

Page 23: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

1 import win32com

2 import time

3 from array import array

4 import random

5 import sys

6 import math

7 from math import *

8 xsi = Application

9 oRoot = Application.ActiveSceneRoot

1011 # main function

12 def ReadLightMap(GroupName):

13 # first create a group to add the lights to

14 xsi.CreateGroup(GroupName, "", "")

15 oFileBrowser = XSIUIToolkit.FileBrowser

16 oFileBrowser.DialogTitle="Please Select LightMap file"

17 oFileBrowser.Filter = "LightMap (*.lightmap)|*.lightmap||"

18 oFileBrowser.ShowOpen()

1920 if oFileBrowser.FilePathName == "" :

21 print "No file selected"

22 return23 fileName=oFileBrowser.FilePathName

242526 # LightNum used to append to GroupName for the Light

27 LightNum=0

28 # so we open the file for reading

29 lightFile=open(fileName,'r')

30 # read in all the data

31 try :

32 data=lightFile.readlines()

33 #now read through the file and grab data

Monday, 31 January 2011

Page 24: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

1 for line in data :

2 # tokenise the data into tuple light

3 light=line.split()

4 # File Line Format is x,y,z r,g,b, Shadowed[1,0], Intensity

5 # we need to use the constructors for float to ensure we get floats not strings

6 x=float(light[0])

7 y=float(light[1])

8 z=float(light[2])

9 r=float(light[3])

10 g=float(light[4])

11 b=float(light[5])

12 # we convert shad to an int

13 shad=int(light[6])

14 intensity=float(light[7])

15 # create a name for the light

16 LightName=GroupName+"%d" %(LightNum)

17 # now run xsi commands to create the light dome from map

1819 Light=oRoot.AddLight("Point",False,LightName);

20 xsi.SelectObj(LightName, "", 1)

21 xsi.Translate("", x, y, z, "siAbsolute", "siGlobal", "siObj", "siXYZ", "", "", "", "", "", "", "

", "", "", 0, "")

22 Intensity=LightName+".light.soft_light.intensity"

23 xsi.SetValue(Intensity, intensity, "")

24 Shadow=LightName+".light.soft_light.shadow"

25 xsi.SetValue(Shadow, 1, "")

26 xsi.AddToGroup(GroupName, LightName)

27 colour=LightName+".light.soft_light.color.red"

28 xsi.SetValue(colour, r, "")

29 colour=LightName+".light.soft_light.color.green"

30 xsi.SetValue(colour, g, "")

31 colour=LightName+".light.soft_light.color.blue"

32 xsi.SetValue(colour, b, "")

3334 xsi.AddToGroup(GroupName, LightName)

3536 LightNum+=1;

37 finally :

38 # finished with the file so close

39 lightFile.close()

4041 ReadLightMap("NameOfGroup")

Monday, 31 January 2011

Page 25: Python 3 - Bournemouth University · PDF file65 ReadLightMap("/Users/jmacey/teaching/LightTools/images/pisa.lightmap","LightDome",15) Monday, 31 January 2011. XSI Version Monday, 31

Maya Version1 ########################################################################2 # This function is to read a LightMap File from the MedianCutFilter3 # Usage ReadLighMap(Name of file, Name of Light Group)4 # Author Jon Macey [email protected] # Version 1.0 15/1/086 # This is to be used with maya 8.0 and above7 ########################################################################89 # import the maya commands to local namespace mc

10 import maya.cmds as mc11 # main function12 def ReadLightMap(fileName, GroupName):1314 # create a group for the lights15 mc.group( em=True, name=GroupName);16 # LightNum used to append to GroupName for the Light17 LightNum=018 # so we open the file for reading19 lightFile=open(fileName,'r')20 # read in all the data21 try :22 data=lightFile.readlines()23 #now read through the file and grab data24 for line in data :25 # tokenise the data into tuple light26 light=line.split()27 # File Line Format is x,y,z r,g,b, Shadowed[1,0], Intensity28 # we need to use the constructors for float to ensure we get floats

not strings29 x=float(light[0])30 y=float(light[1])31 z=float(light[2])32 r=float(light[3])33 g=float(light[4])34 b=float(light[5])35 # we convert shad to a boolean36 shad=bool(light[6])37 intensity=float(light[7])38 # create a name for the light39 LightName=GroupName+"%d" %(LightNum)4041 # now run maya commands to create the light dome from map42 # create a point light43 #print LightName,x,y,z,r,g,b44 mc.pointLight(name=LightName,position=[x,y,z], rgb=[r,g,b] ,i=

intensity ,rs=shad)45 # select it46 mc.select(LightName,r=True)47 # parent it to the group48 mc.parent(LightName,GroupName ,relative=True)49 LightNum+=1;50 finally :51 # finished with the file so close52 lightFile.close()5354 # to run the script use55 #ReadLightMap("ightmap file ","group name")

Monday, 31 January 2011


Recommended