3

Before building my project, I have to generate a C++ source file through a Python script, using the Meson build system.

Is this the correct way, i.e. consider Python as a generic external command?

# meson.build
r = run_command('python', 'arg1', 'arg2', 'arg3')
if r.returncode() != 0
  error('Error message')
endif

Or, being Meson itself a Python program, is it possible to do the same thing in a more straightforward way?

Pietro
  • 12,086
  • 26
  • 100
  • 193

2 Answers2

2

To make your build definition more robust, you can try to find python executable at first with find_program(). This will stop build with verbose reason if python can't be found (You may alter this behavior by passing required: false as an argument).

Then, to ensure that there are no path issues if your arguments are files or directories, make sure to wrap those with files().

All in all:

python_exe = find_program('python3', 'python')
params = files('file1', 'dir/file2')

r = run_command(python_exe, params, 'arg1', 'arg2')
if r.returncode() != 0
    error('Error message')
endif

You may also consider defining your code-generation via python with actual building targets, e.g. generator() or custom_target(). This way, you can use the code-generation target as a dependency for actual c++ compiling target, therefore, it is guaranteed that code will be generated first and only then compiled.

barsoosayque
  • 329
  • 2
  • 11
  • 1
    This is a more portable method: https://mesonbuild.com/Python-3-module.html#find_python – TingPing Feb 20 '19 at 23:27
  • True, although, it seems to be deprecated. [find_installation()](https://mesonbuild.com/Python-module.html#find_installation) from python module is what they suggest instead. And it's nice because it has some handy features ! – barsoosayque Feb 21 '19 at 04:36
  • @barsoosayque: shouldn't it be: `r = run_command(python_exe, params, 'arg1', 'arg2')` – Pietro Feb 25 '19 at 13:58
1

According to one of the key design considerations behind meson:

Meson has been designed in such a way that the implementation language is never exposed in the build definitions. This makes it possible (and maybe even easy) to reimplement Meson in any other programming language.

So, even though meson is implemented in Python, users may forget about this and concentrate on provided functionality which is, as you found it, extendable with run_command function.

pmod
  • 10,450
  • 1
  • 37
  • 50