Python: Click Package - Having trouble with non ASCII chars & cmd.exe - python

I am writing a command line tool using the Click Python Package:
http://click.pocoo.org/5/
Which is quite usefull but I can't get one issue fixed with that, which is when I enter non ASCII chars as parameter for my Command Line Tool, it will always give me that encoding error:
And yeah I know about encode() and decode() in python, but as you can see in my code I am not touching this string anywhere.
Is it the fault of my console? Am I missing any settings here? I am using Windows 7 cmd.exe and know that Windows likes his own encoding for filenames etc. Do I have to use another console? Tried python one with same result.
The click Documentation states all strings are treated as Unicode...
I would appreciate your help really much.
Installing click is as easy as pip install click
Kind regards,
Marcurion
My Code:
import click
from click_shell import shell
import os
#shell(prompt='Tool > ', intro='some test...', hist_file=os.path.dirname(os.path.realpath(__file__)))
def stRec():
pass
#stRec.command()
#click.argument('name', required=True, type=click.STRING)
def set(name):
print "nothing"
if __name__ == '__main__':
stRec()

I found it out, had to add this on top of the other import statements (all lines are important):
#!/usr/bin/python -S
import sys
reload(sys)
sys.setdefaultencoding("cp1252")
import site
cp1252 is the encoding reported to me by
import locale
print locale.getpreferredencoding()
However the encoding of my "name" parameter was not cp1252 when I got it, had to find out with chardet lib (pip install chardet)that it was actually ISO-8859-9. So since I wanted to create a folder with this argument I encoded it back to cp1252:
#!/usr/bin/python -S
import sys
reload(sys)
sys.setdefaultencoding("cp1252")
import site
import click
from click_shell import shell
import os
import locale
import chardet
#shell(prompt='Tool > ', intro='some test...', hist_file=os.path.dirname(os.path.realpath(__file__)))
def stRec():
pass
#stRec.command()
#click.argument('name', required=True, type=click.STRING)
def set(name):
# Create folder in the folder running this script
folderPath = os.path.join(os.path.split(os.path.abspath(__file__))[0], name)
folderPath = folderPath.decode(str(chardet.detect(bytes(folderPath))['encoding'])).encode(locale.getpreferredencoding())
if not os.path.exists(folderPath):
os.makedirs(folderPath)
if __name__ == '__main__':
stRec()

Related

Python URL call using xdg Linux command

I have been trying to get this simple url call Linux command to run as a python script. However, I keep getting an error for too many arguments in the system() module. Is there is easy fix still using this technique?
import sys
import os
g = str(input('enter search '))
os.system('xdg-open https://',g)
format the command as a single string instead of 2 parameters
import sys
import os
search = str(input('enter search'))
os.system(f'xdg-open https://{search}')

Python: How to import asciidoc3

How can I convert an asciidoc to html using the asciidoc3 python package from within my python script? I'm not able to find a working example. The official docs are oriented mainly towards those who will use asciidoc3 as a command line tool, not for those who wish to do conversions in their python apps.
I'm finding that sometimes packages are refactored with significant improvements and old examples on the interwebs are not updated. Python examples frequently omit import statements for brevity, but for newer developers like me, the correct entry point is not obvious.
In my venv, I ran
pip install asciidoc3
Then I tried...
import io
from asciidoc3.asciidoc3api import AsciiDoc3API
infile = io.StringIO('Hello world')
outfile = io.StringIO()
asciidoc3_ = AsciiDoc3API()
asciidoc3_.options('--no-header-footer')
asciidoc3_.execute(infile, outfile, backend='html4')
print(outfile.getvalue())
and
import io
from asciidoc3 import asciidoc3api
asciidoc3_ = asciidoc3api.AsciiDoc3API()
infile = io.StringIO('Hello world')
asciidoc3_.execute(infile)
Pycharm doesn't have a problem with either import attempt when it does it's syntax check and everything looks right based on what I'm seeing in my venv's site-packages... "./venv/lib/python3.10/site-packages/asciidoc3/asciidoc3api.py" is there as expected. But both of my attempts raise "AttributeError: module 'asciidoc3' has no attribute 'execute'"
That's true. asciidoc3 doesn't have any such attribute. It's a method of class AsciiDoc3API defined in asciidoc3api.py. I assume the problem is my import statement?
I figured it out. It wasn't the import statement. The error message was sending me down the wrong rabbit hole but I found this in the module's doc folder...
[NOTE]
.PyPI, venv (Windows or GNU/Linux and other POSIX OS)
Unfortunately, sometimes (not always - depends on your directory-layout, operating system etc.) AsciiDoc3 cannot find the 'asciidoc3' module when you installed via venv and/or PyPI. +
The solution:
from asciidoc3api import AsciiDoc3API
asciidoc3 = AsciiDoc3API('/full/path/to/asciidoc3.py')

Using Numpy from keyword.py

I want to use NumPy in a Python script that uses pandas to process an Excel file. However, one of my constraints is that my file must be named keyword.py, which causes an import error. The import error is traced back to a line from keyword import iskeyword as _iskeyword in C:\Python27\lib\collections.py, which I assume causes an error because my own keyword.py is overriding the default keyword module. Is there any way to avoid this collision?
Not pretty, but a keyword.py of
if True:
import imp, sys
keyword_loc = imp.find_module("keyword", sys.path[1:])[1]
imp.load_source("keyword", keyword_loc)
import collections
print(collections.Counter)
fails with an AttributeError if we replace True with False, but gives me
(2.7) dsm#notebook:~/coding/kw$ python keyword.py
<class 'collections.Counter'>
as is. This works by finding out where the original keyword library is and manually importing it. After this, any following attempts to import keyword will see that it's already there.
For working with a single script, you can remove the current directory from the import search path. That might be sufficient for working on your TopCoder problem, but I wouldn't recommend it as a long-term solution. (Long-term: don't use file names that mirror the standard library.)
If the following script is called keyword.py, it can be run and the import of collections will not trigger an error.
# keyword.py
# Remove the current directory from the import search path
# This is a hack, but it will be sufficient for working with a
# single script that doesn't import any other modules from the
# current directory.
import sys
sys.path = sys.path[1:]
import collections
print(collections)

How to find the path of a module in python

from aqt import mw
It is from an anki(a program make in python) add-on source code, where can I find the mw file? I found folder /usr/share/anki/aqt, but I didn't find mw folder or mw.py file, where else could it be? Or is there method to display its path?
to identify the type of mw, do type(mw) in your python console. It might be something defined in the __init__.py file of the aqtdir. If 'mw' is a module, then you can try mv.__file__.
Start python interpreter with -v flag, for every import its path will be printed like a comment
Here an example with a funny module:
user#host ~/$ python -v
###
#a bunch of bultin imports
###
>>> import sexmachine
import sexmachine # directory /usr/local/lib/python2.7/dist-packages/sexmachine
# /usr/local/lib/python2.7/dist-packages/sexmachine/__init__.pyc matches /usr/local/lib/python2.7/dist-packages/sexmachine/__init__.py
import sexmachine # precompiled from /usr/local/lib/python2.7/dist-packages/sexmachine/__init__.pyc
You should check this out.
from aqt import mw
print mw.__file__
Edit: wtf? "Trivial answer converted to comment"?

Python 3: how to import a module

I use Windows. Somehow I fail to import my own module.
I prepared:
import sys
sys.path.append(r'C:\Users\Michael\PycharmProjects\timer')
#import timer
print(sys.path)
An extract of what was printed:
site-packages', 'C:\\Users\\Michael\\PycharmProjects\\timer']
In C:\Users\Michael\PycharmProjects\timer I have a file named timer.py
Why is my command import timer incorrect?
Your import statement is commented out, in python you import by just doing import timer without the # in front as used by many compiled languages and their include statements.
The import command is flagged as a comment. Remove the hash tag and it should be fine.

Categories

Resources