Include entire directory in python setup.py data_files

删除回忆录丶 提交于 2019-12-23 07:45:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!