问题
The data_files parameter for setup takes input in the following format:
setup(...
data_files = [(target_directory, [list of files to be put there])]
....)
Is there a way for me to specify an entire directory of data instead, so I don't have to name each file individually and update it as I change implementation in my project?
I attempted to use os.listdir()
, but I don't know how to do that with relative paths, I couldn't use os.getcwd()
or os.realpath(__file__)
since those don't point to my repository root correctly.
回答1:
I don't know how to do that with relative paths
You need to get the path of the directory first, so...
Say you have this directory structure:
cur_directory
|- setup.py
|- inner_dir
|- file2.py
To get the directory of the current file (in this case setup.py), use this:
cur_directory_path = os.path.abspath(os.path.dirname(__file__))
Then, to get a directory path relative to current_directory
, just join some other directories, eg:
inner_dir_path = os.path.join(cur_directory_path, 'inner_dir')
If you want to move up a directory, just use "..
", for example:
parent_dir_path = os.path.join(current_directory, '..')
Once you have that path, you can do os.listdir
For completeness:
If you want the path of a file, in this case "file2.py
" relative to setup.py
, you could do:
file2_path = os.path.join(cur_directory_path, 'inner_dir', 'file2.py')
回答2:
karelv has the right idea, but to answer the stated question more directly:
from glob import glob
setup(
#...
data_files = [
('target_directory_1', glob('source_dir/**')),
('target_directory_2', glob('nested_source_dir/**/*', recursive=True)),
# etc...
],
#...
)
回答3:
import glob
for filename in glob.iglob('inner_dir/**/*', recursive=True):
print (filename)
Doing this, you get directly a list of files relative to current directory.
来源:https://stackoverflow.com/questions/27829754/include-entire-directory-in-python-setup-py-data-files