3ORZ
3ORZ

Reputation: 79

How to call python from c++

I'm Python new comer. I tried to call a python script from c++ like this (in Raspberry Pi).

std::string pythonCommand = "python Callee.py \""+a+"\" "+b;
int res = system(pythonCommand.c_str());

after running I got this.

python: can't open file 'Callee.py': [Errno 2] No such file or directory

But I can run Callee.py with command line successfully and both file stored in same directory.

What was I missing ?

Upvotes: 4

Views: 4576

Answers (2)

You probably are running the python interpreter (and your python Callee.py command) in some strange directory (i.e. in some other directory than what you are expecting).

You could use getcwd(3) before your call to system(3) to find out your current working directory.

You might use the chdir(2) system call (before calling system) to change the directory to something appropriate. See perhaps this.

I recommend also reading Advanced Linux Programming

Read also about Extending and Embedding the Python Interpreter; but if you need to embed some interpreter consider also Guile & Lua.

Upvotes: 3

John.A.Myer
John.A.Myer

Reputation: 75

you can try something like this

system("/work/test/pythonscript.sh")

and define inside this script how your python script is executed/called.

This way you dont trip over format errors (c_string() and "\r" or OS-dependent line endings)

Upvotes: 1

Related Questions