execute_process: how to pass argument to python script

execute_process(COMMAND ${Python3_EXECUTABLE} my_script.py my_arg)

doesn’t work as intended: my_script.py is executed, but does not see the argument my_arg.

Whereas on the command line

$ python3 my_script.py my_args

does work.

As a minimal example, suppose my_script.py is

import sys
print("my_script found argument", sys.argv[1])

This works locally:

% cmake -P run.cmake
-- Found Python3: /usr/bin/python3.9 (found version "3.9.10") found components: Interpreter 
my_script found argument my_arg
% cat my_script.py
import sys
print("my_script found argument", sys.argv[1])
% cat run.cmake
find_package(Python3 REQUIRED COMPONENTS Interpreter)
execute_process(COMMAND ${Python3_EXECUTABLE} my_script.py my_arg)

Can you provide a fuller example that shows the problem?

Thank you very much, Ben.

Things didn’t work in my more complex code because I confused upper and lower case in a variable name.

Apologies, Joachim

Hello everyone,

I faced issue when send back argument from python to Cmake I used
os.environ[“MY_DATA”] = ‘2’
print(os.environ[“MY_DATA”])

and I read the env variable in Cmake was

set(env $ENV{MY_DATA})
message(“Helloo Python your value is : ${env}”)

It not work , Can someone explain for me why

Can you provide the relationship between these two snippets of code? Is the Python script doing the os.environ setting launching CMake somehow? Can you share that?

Hi Ben ,

Thanks for reply

For 2 snippet code I wanted trial to send a message from Python to CMake parents , when it call to Python I trial to export an env variable by Python to use in CMake for other purpose. I used with excute_process to call Python script in CMake parents and message to print value Python return back . But it was not work

A child process cannot set the environment of the parent process, so a Python script setting its environment has no effect on the CMake process calling it via execute_process.

Thanks for your reply Ben .

Are there anyway Python scripts can export env for other scripts use or it just only set its env and other scripts can’t see ? I used to set env variable in CMake and shell. Python scripts use env (export env in shell and set env $ENV{env} in CMake) . I just trial some way to export env variables from Python.

The environment can only be modified for the currently running processes and new processes started (via passing them to the execve or CreateProcess family of APIs).