简体   繁体   English

os.chdir() 通过 c++ 调用时出错

[英]os.chdir() gives error when calling via c++

I've wrote this code to change the working directory of the python to the c++ directory:我编写了这段代码来将 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())");

The output is: output 是:

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'

The strange thing is that with normal python shell "Q:/Q/UVC Luftreinigungsanlage/System/Air Purification Management System" is a valid string for os.chdir() and this works, but I see no difference to this called with the Python.h library. The strange thing is that with normal python shell "Q:/Q/UVC Luftreinigungsanlage/System/Air Purification Management System" is a valid string for os.chdir() and this works, but I see no difference to this called with the Python .h 库。

wdCString is a dangling pointer - working_directory.toStdString() is a temporary object whose lifetime has ended at the next line. wdCString是一个悬空指针 - working_directory.toStdString()是一个临时的 object ,其生命周期已在下一行结束。

You can either extend its lifetime,您可以延长其使用寿命,

const std::string& wd = working_directory.toStdString();
const char * wdCString = wd.c_str();

or pass the pointer directly,或者直接传递指针,

PyObject* pyWd = PyUnicode_FromString(working_directory.toStdString().c_str());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM