【问题标题】:os.chdir() gives error when calling via c++os.chdir() 通过 c++ 调用时出错
【发布时间】: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 风格字符串的方法。
  • 在 Linux 上考虑在 C++ 代码中使用 getcwd(2)。另请参阅POCO
  • 使用Qt 你可以使用QDir::current

标签: python c++ python-embedding


【解决方案1】:

wdCString 是一个悬空指针 - working_directory.toStdString() 是一个临时对象,其生命周期已在下一行结束。

您可以延长其使用寿命,

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

或者直接传指针,

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

【讨论】:

  • 我更改了它,但它仍然给我错误。我也可以将 pyWd 转回 QString 并打印出来,它仍然是预期的路径,所以它显然没有被破坏。
  • @532465747 您无法通过检查确定对象是否有效。未定义的行为令人讨厌。
  • 好的,但遗憾的是它仍然无法正常工作,给出同样的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 1970-01-01
  • 2015-04-28
  • 2018-11-05
相关资源
最近更新 更多