Archive

Archive for the ‘python’ Category

Anaconda3, Windows, command-line arguments

April 16, 2017 Leave a comment

Problem
I installed Anaconda3 on Windows 7, but when I wanted to pass a command-line argument to a script, the script didn’t receive the parameter(s). The command-line arguments were simply ignored.

Solution
I found the solution here. This is a blog post from 2010. This issue is still unresolved…

In short: open the registry editor (regedit), find the key HKEY_CLASSES_ROOT\py_auto_file\shell\open\command , and append the string “%*” (without quotes) to the end of the entry. It should look similar to this:

"C:\Anaconda3\python.exe" "%1" %*
Categories: python, windows Tags: , ,

Python Coding Conventions at AIC

March 8, 2017 Leave a comment
Categories: python Tags: , ,

namedtuple

February 9, 2017 Leave a comment

A namedtuple can be used as a simple class where you want to group together some attributes, you want to name them, and you don’t need any methods. As its name suggests, it’s a tuple, but you can assign names to the attribues.

Example

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])    # name of the "struct" and its attributes
# Point = namedtuple('Point', 'x y')       # it would also work, and it means the same
                                           # the 2nd parameter can be a single space-delimited string

def main():
    p = Point(x=1, y=4)
    print(p)                # Point(x=1, y=4)
    p = Point(1, 4)
    print(p)                # Point(x=1, y=4)
    print(p.x)              # 1
    print(p[0])             # 1
    print(p == (1, 4))      # True
Categories: python Tags: ,

creating a list of strings

February 5, 2017 1 comment

Have you aver written something like this?

>>> li = ["one", "two", "three", "four"]
>>> li
['one', 'two', 'three', 'four']

When I type in all those quotation marks and commas, I always feel sorry for my finger joints. Is there an easier way? Yes, there is:

>>> li = "one two three four".split()
>>> li
['one', 'two', 'three', 'four']
Categories: python Tags: ,

remove punctuations from a text

February 5, 2017 Leave a comment

Problem
You have a text and you want to remove punctuations from it. Example:

in:
"Hello! It is time to remove punctuations. It is easy, you will see."

out:
"Hello It is time to remove punctuations It is easy you will see"

Solution
Let’s see a Python 3 solution:

>>> import string
>>> tr = str.maketrans("", "", string.punctuation)
>>> s = "Hello! It is time to remove punctuations. It is easy, you will see."
>>> s.translate(tr)
'Hello Its time to remove punctuations Its easy youll see'

Docs: str.maketrans(), str.translate().

Categories: python Tags: , ,

4k input limit in terminal

January 23, 2017 Leave a comment

Problem
Today I ran into a strange problem. Take this code:

s = input("text> ")
print(len(s))

If the input is very long, then it is truncated to 4096 characters (I tried it under Linux). The same happens when you do “cat | wc” and paste in a long string. What???

Solution
It turns out that there’s a 4k kernel line length limit on terminal input (link). But how to overcome this problem?

0) Well, probably the best way is not to insert such a long string in the terminal. Pass it through a pipe (“cat long.txt | wc” does work) or read it from a file.

But, if you really want to paste in a long string, here is what you can do:

1) With the command “stty -icanon” you can disable the canonical mode. Paste in the string, and then I think it’s a good idea to enable the canonical mode again with “stty icanon” (link).

2) Under Python I found a simple way. Just “import readline” and it solved the issue for me. I tried it with a 11,000 characters long string and it worked.

Thanks to #python on IRC for helping to solve this issue.

Categories: python Tags: , ,

moving from unipath to pathlib

January 10, 2017 Leave a comment

Unipath is a very nice 3rd-party library for an object-oriented approach to Python file/directory operations. Just look at this sane API:

>>> from unipath import Path
>>> p = Path("/usr/lib/python2.5/gopherlib.py")
>>> p.parent
Path("/usr/lib/python2.5")
>>> p.name
Path("gopherlib.py")
>>> p.ext
'.py'
>>> p.stem
Path('gopherlib')
>>> q = Path(p.parent, p.stem + p.ext)
>>> q
Path('/usr/lib/python2.5/gopherlib.py')
>>> q == p
True

However, a very similar module landed in Python 3 called pathlib. It is almost the same as unipath but since it’s in the standard library, I think I’ll switch to it. It means one less external dependency, which is always a good thing.

Let’s see what it looks like:

>>> from pathlib import Path
>>> p = Path("/usr/lib/python2.5/gopherlib.py")
>>> p.parent
PosixPath('/usr/lib/python2.5')
>>> p.name
'gopherlib.py'
>>> p.suffix    # !!! called suffix, not ext !!!
'.py'
>>> p.stem
'gopherlib'
>>> q = Path(p.parent, p.stem + p.suffix)
>>> q
PosixPath('/usr/lib/python2.5/gopherlib.py')
>>> q == p
True
>>>

One important difference though. Unipath’s Path is a subclass of str, thus whenever a function needs a string, you can pass a Path object. However, it’s not true for pathlib’s PosixPath. It means that if you need the string representation of a PosixPath, you need to convert it manually.

Example:

>>> import os
>>> from pathlib import Path
>>> p = Path("/usr/lib/python2.5/gopherlib.py")
>>> os.path.exists(p)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.5/genericpath.py", line 19, in exists
    os.stat(path)
TypeError: argument should be string, bytes or integer, not PosixPath
>>> os.path.exists(str(p))    # here
False
>>> 

Some other features

>>> from pathlib import Path
>>> Path.home()
PosixPath('/home/jabba')    # Were you also fed up with os.path.expanduser('~') ?
>>> p = Path('/tmp/na.txt')
>>> p.chmod(0o644)
>>> p.exists()
True
>>> p.is_file()
True
>>> p.is_dir()
False
>>> 
>>> p = Path('/tmp/ehh.txt')
>>> p.exists()
False
>>> p.touch()    # At last! We have `touch` in the stdlib!
>>> p.exists()
True

Painless read from / write to file

>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')    # newline is NOT added automatically
18
>>> p.read_text()
'Text file contents'

More details in the official docs.

Categories: python Tags: ,