3
$\begingroup$


I want to get blender to work with argparse. I found the following implementation in blender here and tried to sum it down to this:

import argparse
import sys
argv = sys.argv
if "--" not in argv:
    argv = [] # as if no args are passed
else:
    argv = argv[argv.index("--") + 1:] # get all args after "--"
usage_text = "Run blender in background mode with this script: blender --background --python " + __file__ + " -- [options]"
parser = argparse.ArgumentParser(description=usage_text)
args = parser.parse_args(argv) # In this example we wont use the args

However when executed named as argparse_blender.py like this:

blender -b -P argparse_blender.py --  -h

I get as the last line:

Error: Not freed memory blocks: 216

Is there a way to fix this? If not, is it serious? I care about memory leaks.

$\endgroup$
1
4
$\begingroup$

I had the same issue, so I use try and except to fix this problem in python 3.3 in blender 2.69.

Solution

try:
    args = parser.parse_args(argv)
    do_something(args)
except SystemExit as e:
    print(repr(e))
# END OF FILE

Results

When we run blender like this:

blender --background --python argparse_blender.py -- -h

(Or like this blender --b --P argparse_blender.py -- -h)

We get the desired output:

usage: blender [-h]

Run blender in background mode with this script: blender --background --python argparse_blender.py -- [options]

optional arguments:                                                                                                                                
    -h, --help  show this help message and exit
SystemExit(0,)

found bundled python: [...]/blender/2.69/python

Blender quit

Suggestion

I would write the whole argparse_blender.py like this:

import do_something
import argparse
import sys

argv = sys.argv
if "--" not in argv:
    argv = []
else:
   argv = argv[argv.index("--") + 1:]

## set the prog name to match real usage
parser = argparse.ArgumentParser(
    description = 'Run blender in background mode',
    prog = "blender -b -P "+__file__+" --",
)
try:
    args = parser.parse_args(argv)
    do_something(args)
except SystemExit as e:
    print(repr(e))
# END OF FILE

Because it gives nicer output:

usage: blender -b -P argparse_blender.py -- [-h]

Run blender in background mode

optional arguments:                                                                                                                                
    -h, --help  show this help message and exit
SystemExit(0,)

found bundled python: [...]/blender/2.69/python

Blender quit
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.