如何将文件从 Python 包(站点包)复制到目录?

Eir*_*k M 4 python setuptools python-3.x

情况是这样的:我有一个 Python 库,用于使用自定义协议与其他一些硬件进行通信。无论谁使用此解决方案,都需要一个 C 代码库来实现通信的另一端。

我认为执行此操作的一个简单方法是将文件放入 Python 包中,并提供将文件复制到所选目录的命令。这些文件已正确捆绑,但我不知道如何访问它们。我希望事情会这么简单:

# 'pkgname' is a placeholder for package in site-packages.
shutil.copy('pkgname' + os.sep + 'filename', os.getcwd())
Run Code Online (Sandbox Code Playgroud)

但后来我得到:

FileNotFoundError: [Errno 2] No such file or directory: 'pkgname\\filename'
Run Code Online (Sandbox Code Playgroud)

关于如何解决复制问题有什么建议吗?还是问题本身?

Eir*_*k M 5

Found a working solution, the main thing I was looking for was the first line:

pkgdir = sys.modules['<mypkg>'].__path__[0]
fullpath = os.path.join(pkgdir, <myfile>)
shutil.copy(fullpath, os.getcwd())
Run Code Online (Sandbox Code Playgroud)

Also did a silly error of not import the module in question; guess the obvious bugs are the hardest to find.