【发布时间】:2021-02-18 10:45:24
【问题描述】:
我写了这段代码,将python的工作目录改为c++目录:
Py_Initialize();
// Get the c++ working directory
QString working_directory = QFileInfo(".").absolutePath();
qDebug() << "C++ wd: " << working_directory;
PyRun_SimpleString("import os");
// Import the os module
PyObject* pyOSModule = PyImport_ImportModule("os");
// Convert the std::string to c string
const char * wdCString = working_directory.toStdString().c_str();
// Create python working directory string
PyObject* pyWd = PyUnicode_FromString(wdCString);
// The chdir function of the os module
PyObject* pyChdirFunction = PyObject_GetAttrString(pyOSModule,(char*)"chdir");
// Call the chdir method with the working directory as argument
PyObject_CallFunction(pyChdirFunction, "s", pyWd);
PyRun_SimpleString("print('Python wd: ' + os.getcwd())");
输出是:
C++ wd: "Q:/Q/UVC Luftreinigungsanlage/System/Air Purification Management System"
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '\x01'
奇怪的是,对于普通的 python shell,“Q:/Q/UVC Luftreinigungsanlage/System/Air Purification Management System”是 os.chdir() 的有效字符串,并且可以正常工作,但我认为这与所谓的没有区别使用 Python.h 库。
【问题讨论】:
-
working_directory.toStdString()的结果是临时的,其c_str()值随之消失。尝试另一种获取 C 风格字符串的方法。 -
使用Qt 你可以使用QDir::current
标签: python c++ python-embedding