python中import的用法,python為什么import不了_python – 為什么PyImport_Import無法從當前目錄加載模塊?

 2023-10-08 阅读 27 评论 0

摘要:我正在嘗試運行embedding example并且我無法從當前工作目錄加載模塊,除非我將其顯式添加到sys.path然后它可以工作:PyRun_SimpleString("import sys");python中import的用法,PyRun_SimpleString("sys.path.append(\".\")");Python不應該在當前

我正在嘗試運行embedding example并且我無法從當前工作目錄加載模塊,除非我將其顯式添加到sys.path然后它可以工作:

PyRun_SimpleString("import sys");

python中import的用法,PyRun_SimpleString("sys.path.append(\".\")");

Python不應該在當前目錄中查找模塊嗎?

Edit1:嘗試導入模塊:

python import error。Py_Initialize();

PyRun_SimpleString("import multiply");

它仍然失敗,出現以下錯誤:

python from?Traceback (most recent call last):

File "", line 1, in

ImportError: No module named multiply

import Python、Edit2:從sys.path docs:

If the script directory is not available (e.g. if the interpreter is

invoked interactively or if the script is read from standard input),

path[0] is the empty string, which directs Python to search modules

in the current directory first.

不確定它的含義是不可用的,但如果我打印sys.path [0]它不是空的:

/usr/lib/pymodules/python2.7

解決方法:

您需要調用PySys_SetArgv(int argc,char ** argv,int updatepath)才能使相對導入生效.如果updatepath為0,這將把正在執行的腳本的路徑添加到sys.path(有關更多信息,請參閱docs).

以下應該做的伎倆

#include

int

main(int argc, char *argv[])

{

Py_SetProgramName(argv[0]); /* optional but recommended */

Py_Initialize();

PySys_SetArgv(argc, argv); // must call this to get sys.argv and relative imports

PyRun_SimpleString("import os, sys\n"

"print sys.argv, \"\\n\".join(sys.path)\n"

"print os.getcwd()\n"

"import thing\n" // import a relative module

"thing.printer()\n");

Py_Finalize();

return 0;

}

標簽:python,linux,python-2-7,python-embedding

來源: https://codeday.me/bug/20190928/1829663.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/128777.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息