Yes, Blender's Python can read command line arguments.
- Python can read all arguments passed to Blender via
(just the same as you would in
- Blender will ignore all arguments after:
(double dash with no arguments, as documented in the
- Scripts can check for
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.
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.
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.
-- is not always needed, you can check for it like this.
argv = sys.argv
index = argv.index("--") + 1
index = len(argv)
argv = argv[index:]
Note that using
argparse is optional, you can simply do checks such as:
if "--myarg" in argv:
... 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).