Python How can I get the version number from a .whl file - python

Because of some custom logging I would like to get the version number from a wheel file.
I could of course just parse the filename, but my guess is there would be a better way to do this.

You can also use pkginfo e.g.
from pkginfo import Wheel
w = Wheel(r'C:\path\to\package.whl')
print(w.version)

What I did for now is:
Get the package info and put it into a dict:
def get_package_info():
info_dict = {}
with open(os.path.join(glob.glob("./*.egg-info")[0], "PKG-INFO"), "r") as info:
for i in info:
i = i.split(":")
info_dict[i[0].strip()] = i[1].strip()
return info_dict
Now I can get the Verion from this dictionary.
If someone does have a better approach at this, please let me know.

A simple parsing of the wheel's filename should be enough:
>>> 'torch-1.8.1-cp39-cp39-manylinux1_x86_64.whl'.split('-')[1]
'1.8.1'
If you want to be more sophisticated, you can also use wheel-filename to do this parsing for you:
>>> from wheel_filename import parse_wheel_filename
>>> pwf = parse_wheel_filename('pip-18.0-py2.py3-none-any.whl')
>>> pwf.version
'18.0'
If you just need to compute it quickly for a single package, you can use this codepen page I created, to get version and more details from a wheel's filename: https://codepen.io/chaitan94/full/mdWEeBp

Related

How to check the type of file to be downloaded from a link

I was trying to download a file from a link using the following line of code:
urllib.request.urlretrieve('http://ipfs.io/ipfs/QmcgBRy',f'{UNKNOWN_FACES_DIR}\\sample2.mp4')
But the thing is I don't know what type of file is stored in the link and hence cant give an appropriate file extension before downloading it.
Is there any way to get to know the type of file i.e. .jpg, .jpeg, .mp4 etc. before downloading it?
Using pure urllib, you can get the content type from the following:
import urllib
url = 'https://i.imgur.com/Woi6pwf.jpg'
urllib.request.urlopen(url).info()['content-type']
which returns:
'image/jpeg'
You can use the Python-Magic to find the MIME-type of the file. I guess this is the best library to be used for this purpose. You can do like this
import magic
magic.from_file("testdata/test.pdf")
# OUTPUT
# >>> 'PDF document, version 1.2'
Recommended Version
import magic
magic.from_buffer(open("testdata/test.pdf").read(2048))
# OUTPUT
# >>> 'PDF document, version 1.2'

Pyexcel, how to save a dict to csv file with pyexcel?

This part of the topic is solved, see my last answer to this topic.
I'm having trouble to save a dictionary using the pyexcel module.
I instaled the pyxecel module with pip3 install pyexcel
So I have a dictionary and I'm doing this:
import pyexcel as pe
myDict = {...}
pe.save_as(dict = myDict, dest_file_name = "dest_file.xls")
In my terminal, when I compile the code, it prints myDict but just after I have this:
Otherwise unrecognized parameters were given.
terminal output
I look for a solution and it could be related to this: https://pyexcel-io.readthedocs.io/en/latest/pyinstaller.html
But I don't understand how to use the --hiden-import in my code or terminal? When I use this in my code I have a syntax error.
Can someone help me, please?
Thank you in advance.
edit: use pe.save_as(adict = myDict, dest_file_name = "dest_file.xls") to solve the problem.
The reason that this is failing is because the method call save_as() doesn't accept a parameter named dict. According to the documentation, providing a dict should either be done via the adict or with_keys parameters:
pe.save_as(adict = myDict, dest_file_name = "dest_file.xls")

Path to lib/pythonX.Y/no-global-site-packages.txt

What is the official way to get the path of lib/pythonX.Y/no-global-site-packages.txt?
I would like to guess and use sys.version in a way which is finally slightly different.
Looking at the source:
import site
site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))
no_global_file = os.path.join(site_mod_dir, 'no-global-site-packages.txt')

Using multiple keywords in xattr via _kMDItemUserTags or kMDItemOMUserTags

While reorganizing my images, in anticipation of OSX Mavericks I am writing a script to insert tags into the xattr fields of my image files, so I can search them with Spotlight. (I am also editing the EXIF just to be safe.)
My questions are:
Which attribute is the best to use? _kMDItemUserTags seems to be the OSX version, but kMDItemOMUserTags is already in use by OpenMeta. I would ideally like something that will be Linux and OSX forward compatible.
How do I set multiple tags? Are the comma- or space-delimited or something else?
As an example, using the python xattr module, I am issuing these commands:
xattr.setxattr(FileName, "_kMDItemUserTags", "Name - Sample")
xattr.setxattr(FileName, "kMDItemOMUserTags", "Name,Institution,Sample")
I have also seen mention of these tags: kOMUserTags and kMDItemkeywords but don't know if they are likely to be implemented...
EDIT: Further investigation has shown that for things to be searchable in 10.8,
You need to preface the kMD with com.apple.metadata:
You have to either hex-encode or wrap in a plist.
This python code will generate the tag for kMDItemFinderComment which is searchable in spotlight...
def writexattrs(F,TagList):
""" writexattrs(F,TagList):
writes the list of tags to three xattr field:
'kMDItemFinderComment','_kMDItemUserTags','kMDItemOMUserTags'
This version uses the xattr library """
plistFront = '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><array>'
plistEnd = '</array></plist>'
plistTagString = ''
for Tag in TagList:
plistTagString = plistTagString + '<string>{}</string>'.format(Tag)
TagText = plistFront + plistTagString + plistEnd
OptionalTag = "com.apple.metadata:"
XattrList = ["kMDItemFinderComment","_kMDItemUserTags","kMDItemOMUserTags"]
for Field in XattrList:
xattr.setxattr (F,OptionalTag+Field,TagText.encode('utf8'))
# Equivalent shell command is xattr -w com.apple.metadata:kMDItemFinderComment [PLIST value] [File name]
I could not get it to work recursively on a folder with reliable results.
If you are worried about compatibility you have to set both of the attributes _kMDItemUserTags and kMDItemOMUserTags. I don't think there's a different solution since all the new OS X apps will use the former attribute, while the old apps still use the latter. This is just my speculation, but I guess OpenMeta will eventually be discontinued in favor of the new native API. Looking to the future you can use the _kMDItemUserTags attribute for your new apps/scripts even in Linux environment.
The tags are set as a property list-encoded array of strings as you have figured out. I don't know if it is a requirement but the OS X encodes the property list in the binary format and not in XML as you did.
I adapted your code to use binary property list as attribute values and everything worked. Here's my code. I am using biplist library which you can get with easy_install biplist.
import xattr
import biplist
def write_xattr_tags(file_path, tags):
bpl_tags = biplist.writePlistToString(tags)
optional_tag = "com.apple.metadata:"
map(lambda a: xattr.setxattr(file_path, optional_tag + a, bpl_tags),
["kMDItemFinderComment", "_kMDItemUserTags", "kMDItemOMUserTags"])
Tested with files and directories using tag:<some_tag> in Spotlight.
Hope this helps.
Note: I am using OS X Lion in this answer but it should work on Mavericks without any problems.
Edit: If you want to apply the tags to the contents of a directory it has to be done individually for every file since the xattr python module doesn't have the recursive option.

single py file for convert rst to html

I have a blog written in reStructuredText which I currently have to manually convert to HTML when I make a new post.
I'm writing a new blog system using Google App Engine and need a simple way of converting rst to HTML.
I don't want to use docutils because it is too big and complex. Is there a simpler (ideally single python file) way I can do this?
docutils is a library that you can install. It also installs front end tools to convert from rest to various formats including html.
http://docutils.sourceforge.net/docs/user/tools.html#rst2html-py
This is a stand alone tool that can be used.
Most converters will exploit the docutils library for this.
The Sphinx documentation generator Python library includes many restructured text (RST) command-line converters.
Install Sphinx:
$ pip install sphinx
Then use one of the many rst2*.py helpers:
$ rst2html.py in_file.rst out_file.html
Have a look at the instructions for hacking docutils. You don't need the whole docutils to produce a html from rst, but you do need a reader, parser, transformer and writer. With some effort you could combine all of these to a single file from the existing docutils files.
Well you could try it with the following piece of code, usage would be:
compile_rst.py yourtext.rst
or
compile_rst.py yourtext.rst desiredname.html
# compile_rst.py
from __future__ import print_function
from docutils import core
from docutils.writers.html4css1 import Writer,HTMLTranslator
import sys, os
class HTMLFragmentTranslator( HTMLTranslator ):
def __init__( self, document ):
HTMLTranslator.__init__( self, document )
self.head_prefix = ['','','','','']
self.body_prefix = []
self.body_suffix = []
self.stylesheet = []
def astext(self):
return ''.join(self.body)
html_fragment_writer = Writer()
html_fragment_writer.translator_class = HTMLFragmentTranslator
def reST_to_html( s ):
return core.publish_string( s, writer = html_fragment_writer )
if __name__ == '__main__':
if len(sys.argv)>1:
if sys.argv[1] != "":
rstfile = open(sys.argv[1])
text = rstfile.read()
rstfile.close()
if len(sys.argv)>2:
if sys.argv[2] != "":
htmlfile = sys.argv[2]
else:
htmlfile = os.path.splitext(os.path.basename(sys.argv[1]))[0]+".html"
result = reST_to_html(text)
print(result)
output = open(htmlfile, "wb")
output.write(result)
output.close()
else:
print("Usage:\ncompile_rst.py docname.rst\nwhich results in => docname.html\ncompile_rst.py docname.rst desiredname.html\nwhich results in => desiredname.html")
Building the doc locally
Install Python.
Clone the forked repository to your computer.
Open the folder that contains the repository.
Execute: pip install -r requirements.txt --ignore-installed
Execute: sphinx-build -b html docs build
The rendered documentation is now in the build directory as HTML.
If Pyfunc's answer doesn't fit your needs, you could consider using the Markdown language instead. The syntax is similar to rst, and markdown.py is fairly small and easy to use. It's still not a single file, but you can import it as a module into any existing scripts you may have.
http://www.freewisdom.org/projects/python-markdown/

Categories

Resources