简体   繁体   中英

How can I copy files from a Python package (site-packages) to a directory?

The situation is this: I have a Python library that serves to communicate with some other hardware using a custom protocol. Whoever uses this solution needs a library in C code to implement the other end of the communications.

I figured that a easy way to do this is to put the files in the Python package and provide a command that copies the files to a directory of choice. The files are bundled correctly, but I can't figure how to access them. I was hoping it would be this easy:

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

But then I get:

FileNotFoundError: [Errno 2] No such file or directory: 'pkgname\\filename'

Any suggestion on how to fix the copy issue? Or the problem itself?

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())

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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