Sunday, 17 February 2019

Setuptools: How to make sure file generated by packed code be deleted by pip

I have a simple code named main.py that generates a folder and a file within it:

import os
def main():
    path = os.path.join(os.path.dirname(__file__), 'folder')

    if not os.path.isdir(path):
        os.mkdir(path)

    with open(os.path.join(path, 'file.txt'), 'w+') as f:
        f.write('something')


if __name__ == '__main__':
    main()

If this script run in a folder, then the structure should be like:

.
├── main.py
└── folder
    └── file.txt


I use a setup.py file to pack the code up, where I assigned an entry point named foo. The setup.py looks like:

from setuptools import setup  
setup(
    name='mypack',
    entry_points={
        'console_scripts': ['foo=mypack.main:main'],
    },
    packages=['mypack'],
    package_data={'': '*.txt'},
    include_package_data=True
)

I packed the code with the structure below:

.
├── mypack
│   └── main.py
└── setup.py

And I install it by pip install . in the root directory. Then I run foo, it indeed generated a folder and a file. Then I uninstall it by pip uninstall mypack, the output in the terminal shows :

Uninstalling mypack-0.0.0:
  Would remove:
    d:\programdata\envs\testsetup\lib\site-packages\mypack-0.0.0-py3.6.egg-info
    d:\programdata\envs\testsetup\lib\site-packages\mypack\main.py
    d:\programdata\envs\testsetup\scripts\foo-script.py
    d:\programdata\envs\testsetup\scripts\foo.exe
Proceed (y/n)? y
  Successfully uninstalled mypack-0.0.0

The folder\file.txt didn't deleted by pip uninstall, also the output of it didn't mention anything about folder\file.txt


Then I pack the code with the structure below:

.
├── mypack
│   ├── __init__.py
│   └── main.py
└── setup.py

Where the __init__.py was an empty file. I did the same procedure, that is: pip install . -> foo -> pip uninstall mypack, then the output in the terminal is:

Uninstalling mypack-0.0.0:
  Would remove:
    d:\programdata\envs\testsetup\lib\site-packages\mypack-0.0.0-py3.6.egg-info
    d:\programdata\envs\testsetup\lib\site-packages\mypack\*
    d:\programdata\envs\testsetup\scripts\foo-script.py
    d:\programdata\envs\testsetup\scripts\foo.exe
  Would not remove (might be manually added):
    d:\programdata\envs\testsetup\lib\site-packages\mypack\folder\file.txt
Proceed (y/n)? y
  Successfully uninstalled mypack-0.0.0

This time, folder\file.txt was mentioned in the output of pip uninstall, but was not automatically removed by pip.


So my questions:

  • Why there is a difference between with and without __init__.py
  • Is there any method that can make pip automatically remove folder\file.txt like that in my example?


from Setuptools: How to make sure file generated by packed code be deleted by pip

1 comment: