Search code examples
pythoncommand-linescriptingblender

How to run a python script taking arguments with blender?


I have a script I want to run within blender to generate AO maps (script was given to me and the source guarantees it works).

I try to run the script as follows:

blender --background --python /opt/ff/product_builder/furniture_builder/generate_ao_maps.py --input_dir /tmp/test.obj --output_dir /tmp/test.png --mode ao

Which produces:

AL lib: (EE) UpdateDeviceParams: Failed to set 44100hz, got 48000hz instead
found bundled python: /usr/share/blender/2.79/python
Traceback (most recent call last):
  File "/opt/ff/product_builder/furniture_builder/generate_ao_maps.py", line 195, in <module>
    main()
  File "/opt/ff/product_builder/furniture_builder/generate_ao_maps.py", line 178, in main
    args = parse_args()
  File "/opt/ff/product_builder/furniture_builder/generate_ao_maps.py", line 21, in parse_args
    return parser.parse_args(os.getenv(BLENDER_ENV).split(' '))
AttributeError: 'NoneType' object has no attribute 'split'
Error: File format is not supported in file '/tmp/test.obj'

Blender quit

If I run this same script without blender (but with the argument) it tells me:

Traceback (most recent call last):
  File "/opt/ff/product_builder/furniture_builder/generate_ao_maps.py", line 5, in <module>
    import bpy
ImportError: No module named bpy

What do I need to do to pass the parameters to the script and get it working?


Solution

  • Firstly, blender processes its cli args in the order they are given, so your example will start in the background, run a script, then set the input_dir... This will most likely not have the result you are after.

    The problem with your script failing is that the arg passed to os.getenv() needs to be a string that is the name of a shell environment variable, if you are using bash you need to export the variable to put it into the environment before you start blender.

    export BLENDER_ARGS="arg1 arg2"
    blender -b myfile.blend --python myscript.py
    

    If you are using a csh then use setenv BLENDER_ARGS "arg1 arg2"

    Then in your py script, you use os.getenv('BLENDER_ARGS').split(' ')

    Note that each shell instance is a separate environment, you need to set the variables in the same instance that starts blender.

    You may also be interested in passing cli arguments to the script as explained in response to this question.