Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 723
Eirik M Avatar asked Oct 28 '25 09:10

Eirik M


1 Answers

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.

like image 132
Eirik M Avatar answered Oct 30 '25 23:10

Eirik M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!