Yes, Blender's Python can read command line arguments.
In summary:
- Python can read all arguments passed to Blender via
sys.argv
(just the same as you would in Python
)
- Blender will ignore all arguments after:
--
(double dash with no arguments, as documented in the --help
message)
- Scripts can check for
--
in sys.argv
and ignore all arguments beforehand.
So Python and Blender always see the same arguments, Blender knows not to interpret arguments after --
and as the script author it's up to you not to interpret Blender's arguments before --
.
This is done so other regular Blender arguments can be passed after --python
, so you could for example pass:
blender --python script.py --render-frame 2..10
... to run a script then render frames 2 to 10.
Example:
Script: mytest.py
import sys
argv = sys.argv
argv = argv[argv.index("--") + 1:] # get all args after "--"
print(argv) # --> ['example', 'args', '123']
Execute like this:
blender --background test.blend --python mytest.py -- example args 123
Having spaces around --
is important, this is a signal that Blender should stop parsing the arguments and allows you to pass your own arguments to Python.
Further information:
For a more comprehensive script example, background_job.py
is a Python template which comes with Blender,
this uses Python's argparse
module, for more flexible handling of arguments.
If you want to have comprehensive arguments for your script with a --help
message, Look into argparse
, general Python docs on the module can be used.
Note: if --
is not always needed, you can check for it like this.
import sys
argv = sys.argv
try:
index = argv.index("--") + 1
except ValueError:
index = len(argv)
argv = argv[index:]
Note that using argparse
is optional, you can simply do checks such as:
if "--myarg" in argv:
do_stuff()
... but I've found as soon as you want to pass values to arguments, this becomes a hassle and its generally better of to use argparse
to begin with, unless...
- You're making a quick test and only need primitive argument handling.
- You have a good reason to spend time doing your own argument parsing, and
argparse
can't handle your use-case (although this is rare in my experirnce, as argparse is flexible enough for most use-cases).