glibc strverscmp called from python
Sujet : glibc strverscmp called from python
De : vallor (at) *nospam* cultnix.org (vallor)
Groupes : comp.lang.pythonDate : 21. Jun 2024, 00:13:51
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v529iv$2lkuv$3@dont-email.me>
User-Agent : Pan/0.159 (Vovchansk; 873418b; Linux-6.9.5)
So there's been discussion in comp.lang.c and comp.unix.shell
about doing a "versionsort(3)" type sort on a list
of parameters. glibc offers strverscmp(3) for this type
of sort, and here I am posting a q&d python program to expose
that to its sort routine for commentary and future reference.
Caveat: I know just enough python to be dangerous -- wrote
this using ChatGPT. It is a learning experience, comments
very much appreciated.
- -%<- -
#!/usr/bin/python3
import ctypes
from ctypes import c_char_p, c_int
import os
import sys
# Load the C standard library (libc)
libc = ctypes.CDLL("libc.so.6")
# Define the prototype of strverscmp
# int strverscmp (const char *s1, const char *s2)
libc.strverscmp.argtypes = [c_char_p, c_char_p]
libc.strverscmp.restype = c_int
# Define a comparison function for Python sorting
def version_compare(x, y):
return libc.strverscmp(x.encode('utf-8'), y.encode('utf-8'))
# Define a key function for sorting
def version_key(s):
class K:
def __init__(self, s):
self.s = s
def __lt__(self, other):
return version_compare(self.s, other.s) < 0
def __gt__(self, other):
return version_compare(self.s, other.s) > 0
def __eq__(self, other):
return version_compare(self.s, other.s) == 0
def __le__(self, other):
return version_compare(self.s, other.s) <= 0
def __ge__(self, other):
return version_compare(self.s, other.s) >= 0
def __ne__(self, other):
return version_compare(self.s, other.s) != 0
return K(s)
# Function to escape special characters
def shell_escape(s):
return s.replace(" ", "\ ").replace("\n", "\n").replace("\t", "\t")
# Parse command-line arguments
args = sys.argv[1:]
# Sort the list using the version key
sorted_args = sorted(args, key=version_key)
# Print each sorted, escaped value on a new line
for arg in sorted_args:
print(shell_escape(arg))
- -%<- -
--
-v
Date | Sujet | # | | Auteur |
21 Jun 24 | glibc strverscmp called from python | 1 | | vallor |
Haut de la page
Les messages affichés proviennent d'usenet.
NewsPortal