git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Python in Blender. Writing information to a file.


Paul St George wrote:

> I am using Python 3.5 within Blender. I want to collect values of the
> current settings and then write all the results to a file.
> 
> I can see the settings and the values in the Python console by doing
> this for each of the settings
> |
> |
> 
> |print(?Focal length:?,bpy.context.object.data.lens)|
> 
> ---Focal length: 35.0
> 
> 
> or I can do many at a time like this:
> 
> |print("Plane rotation
> X:",bpy.data.objects["Plane"].rotation_euler[0],"\nPlane rotation
> Y:",bpy.data.objects["Plane"].rotation_euler[1],"\nPlane rotation
> Z:",bpy.data.objects["Plane"].rotation_euler[2])|
> 
> ---Plane rotation X: 0.0
> ---Plane rotation Y: 0.0
> ---Plane rotation Z: 0.0
> 
> 
> My question:
> How do I write all the results to a file? I have tried file.write but
> can only write one argument at a time. Is there a better way to open a
> file, write the collected information to it and then close the file?
> 

The print() function has a keyword-only file argument. So:

with open(..., "w") as outstream:
    print("Focal length:", bpy.context.object.data.lens, file=outstream)

> |print("Plane rotation
> X:",bpy.data.objects["Plane"].rotation_euler[0],"\nPlane rotation
> Y:",bpy.data.objects["Plane"].rotation_euler[1],"\nPlane rotation
> Z:",bpy.data.objects["Plane"].rotation_euler[2])|

This looks messy to me. I' probably use intermediate variables

x, y, z = bpy.data.objects["Plane"].rotation_euler
print(
    "Plane rotation X:", x,
    "Plane rotation Y:", y,
    "Plane rotation Z:", z,
    file=outstream, sep="\n"
)

or even a loop.