Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while calling python via std::system

Tags:

c++

python

std

cmd

qt

When I try to call python in c++ using this:

QString command = "cd C:\\python\\python37 && python C:\\projects\\file_editor.py" 
QByteArray ba = command.toLocal8Bit();
const char *c_str2 = ba.data();
std::system(c_str2)

I get this error:

Fatal Python error: initfsencoding: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

Any ideas how to fix this?

edit: My python related path in PATH variable is:

C:\python\python37\Scripts

and i can use Qt and i tried this as well:

QProcess process;
QStringList pythonCommandArguments = QStringList() << "C:\\projects\\file_editor.py"
process.start("python", pythonCommandArguments);

but then i get this error:

QProcess: Destroyed while process ("python") is still running.
like image 944
Matthijs990 Avatar asked Nov 19 '19 15:11

Matthijs990


1 Answers

There is no need to cd into the directory of the python interpreter.

On the other hand many projects (if not nicely coded) might require you cd into the project's directory.

if nicely coded no cd at all is required

I would also use the py.exe wrapper, that is installed under windows it is intended to pick the right executable and might take care of some env vars as well. If you have multiple python versions installed I can show you how to select the right version with py.exe.

Try following two options:

QString command = "py.exe C:\\projects\\file_editor.py"
QString command = "cd C:\\projects && py.exe C:\\projects\\file_editor.py"

If you have encoding problems, then set the environment variable PYTHONIOENCODING with putenv() to your desired encoding 'utf-8' / 'cp1252' or whatever you like.

I suggest you try first from the cmd line and only if you get it working from there you try it from C++

Example:

cd c:\projects
echo just some_text > stdin.txt
set PYTHONIOENCODING=cp1252
type stdin.txt | py.exe C:\projects\file_editor.py

I use the type stdin.txt | py.exe ... trick so, that I can simulate calling python without being attched to a console.

I don't have a windows PC with C++ installed, so I cannot test. but hopefully this (using py.exe and setting PYTHONIOENCODING explicitely) should put you on the right track

like image 89
gelonida Avatar answered Sep 29 '22 06:09

gelonida