sachinraja / simple-icons-py

python wrapper for simple-icons
https://pypi.org/project/simpleicons/
MIT License
18 stars 3 forks source link

get_xml(), get_xml_bytes() and get_str() not working #1

Closed fbernhart closed 3 years ago

fbernhart commented 3 years ago

It seems like the three functions get_xml(), get_xml_bytes() and get_str() aren't working.

Minimal reproducible example:

from simpleicons.icon_xml import get_xml

github_icon = get_xml("github")

Throwing this error:

Traceback (most recent call last):
  File "/home/fbernhart/.config/JetBrains/PyCharmCE2021.1/scratches/scratch_4.py", line 3, in <module>
    github_icon = get_xml("github")
  File "/mnt/Daten/Python/Python_Divers/venv/lib/python3.9/site-packages/simpleicons/icon_xml.py", line 41, in get_xml
    tree = get_et(icon_name)
  File "/mnt/Daten/Python/Python_Divers/venv/lib/python3.9/site-packages/simpleicons/icon_xml.py", line 28, in get_et
    return ET.parse(f"simpleicons/icons/{icon_name.lower()}.svg")
  File "/usr/local/lib/python3.9/xml/etree/ElementTree.py", line 1229, in parse
    tree.parse(source, parser)
  File "/usr/local/lib/python3.9/xml/etree/ElementTree.py", line 569, in parse
    source = open(source, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'simpleicons/icons/github.svg'

Process finished with exit code 1

The same happens for

from simpleicons.icon_xml import get_xml_bytes

github_bytes = get_xml_bytes("github")

and

from simpleicons.icon_xml import get_str

github_str = get_str("github")

Looking at the icon_xml.py file, the error happens because you're trying to access simpleicons/icons/github.svg. This might be working if you're testing your code locally and have your tests in the same directory, but it doesn't work while installing simpleicons as a package through pip. Because simpleicons/icons/github.svg isn't located inside the current working directory (from where the script is called).

I'm not very familiar with opening a file from within a package, but I gave it a few tries and came up with this solution. It should work by replacing

return ET.parse(f"simpleicons/icons/{icon_name.lower()}.svg")

with

    import sys
    package_path = sys.modules[__package__].__path__[0]

    return ET.parse(f"{package_path}/icons/{icon_name.lower()}.svg")

the same for the get_str() function.

But let me know if you've got a better idea. 😊

sachinraja commented 3 years ago

I think these should simply be deleted and integrated with the existing icon class. This would allow for a simpler API.

sachinraja commented 3 years ago

I just went ahead and tried switching them to methods of the Icon class and it worked quite well. Let me know if you agree that this way is better. This, again, reduces dependence on the filesystem.