0

I want to run a python script for a blend file within blender and I want to give the command from terminal. Blender has this option as follows:

blender -b -P python_script_path.py

But I want to pass some command line arguments to the python script. Is it possible to do this? If yes, how?

Nagabhushan S N
  • 341
  • 1
  • 9

1 Answers1

1

You can do something like this. Run an inline python script that will call a string and run it as it's own shell command.

# test_run.py
# The test file to run.

import sys

arg1 = sys.argv[1] arg2 = sys.argv[2]

if name == "main": string = f""" Argument 1: {arg1} Argument 2: {arg2} """ print(string)

Then the command that you would in the terminal. If you wanted to run that script alone, with it's two arguments.

python3 ~/scripts/random/test_run.py first_arg second_arg

So then use the subprocess module, which allows you to call shell commands from within python. Throw that into the blender command line with the argument --python-text and you should get.

blender -b --python-expr "import subprocess; subprocess.run('python3 ~/scripts/random/test_run.py first_arg second_arg', shell=True)"

You might have to change the part that says python3 to the python that runs natively with blender. I'm running a custom install of blender and I haven't configured the command line to run as normal, it's just a symlink to the .exe so I'm not sure about the exact specifics of running it in the Blender specific python environment.

But I think the mechanics of how to do it are all there.

Jakemoyo
  • 4,375
  • 10
  • 20
  • 1
    Thanks! This is amazing :) – Nagabhushan S N May 19 '22 at 13:45
  • Hi, I tried this, but I'm getting the following error: Error: text block not found import subprocess; subprocess.run('python PropertiesSetter.py depth optical_flow surface_normals positions', shell=True). Any idea why I'm getting this error? Also, in this question, the argument python-text specifies the name of python code already written into the blend file. So, I'm wondering if specifying code would actually work. – Nagabhushan S N May 19 '22 at 16:11
  • 2
    @NagabhushanSN You can execute Python from the Blender command line using --python-expr <expression> See Python Options in the manual. You have to be very careful with command line quoting. – Marty Fouts May 19 '22 at 18:20
  • Lol yep, I glazed over it and put the wrong line in my answer. Updated. – Jakemoyo May 20 '22 at 14:49