Hiển thị các bài đăng có nhãn Python-Windows-utilities. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn Python-Windows-utilities. Hiển thị tất cả bài đăng

Thứ Tư, 1 tháng 3, 2017

Show error numbers and codes from the os.errno module

By Vasudev Ram

While browsing the Python standard library docs, in particular the module os.errno, I got the idea of writing this small utility to display os.errno error codes and error names, which are stored in the dict os.errno.errorcode:

Here is the program, os_errno_info.py:
from __future__ import print_function
'''
os_errno_info.py
To show the error codes and
names from the os.errno module.
Author: Vasudev Ram
Copyright 2017 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: https://jugad2.blogspot.com
Product store: https://gumroad.com/vasudevram
'''

import sys
import os

def main():

print("Showing error codes and names\nfrom the os.errno module:")
print("Python sys.version:", sys.version[:6])
print("Number of error codes:", len(os.errno.errorcode))
print("{0:>4}{1:>8} {2:<20} {3:<}".format(\
"Idx", "Code", "Name", "Message"))
for idx, key in enumerate(sorted(os.errno.errorcode)):
print("{0:>4}{1:>8} {2:<20} {3:<}".format(\
idx, key, os.errno.errorcode[key], os.strerror(key)))

if __name__ == '__main__':
main()
And here is the output on running it:
$ py -2 os_errno_info.py >out2 && gvim out2
Showing error codes and names
from the os.errno module:
Python sys.version: 2.7.12
Number of error codes: 86
Idx Code Name Message
0 1 EPERM Operation not permitted
1 2 ENOENT No such file or directory
2 3 ESRCH No such process
3 4 EINTR Interrupted function call
4 5 EIO Input/output error
5 6 ENXIO No such device or address
6 7 E2BIG Arg list too long
7 8 ENOEXEC Exec format error
8 9 EBADF Bad file descriptor
9 10 ECHILD No child processes
10 11 EAGAIN Resource temporarily unavailable
11 12 ENOMEM Not enough space
12 13 EACCES Permission denied
13 14 EFAULT Bad address
14 16 EBUSY Resource device
15 17 EEXIST File exists
16 18 EXDEV Improper link
17 19 ENODEV No such device
18 20 ENOTDIR Not a directory
19 21 EISDIR Is a directory
20 22 EINVAL Invalid argument
21 23 ENFILE Too many open files in system
22 24 EMFILE Too many open files
23 25 ENOTTY Inappropriate I/O control operation
24 27 EFBIG File too large
25 28 ENOSPC No space left on device
26 29 ESPIPE Invalid seek
27 30 EROFS Read-only file system
28 31 EMLINK Too many links
29 32 EPIPE Broken pipe
30 33 EDOM Domain error
31 34 ERANGE Result too large
32 36 EDEADLOCK Resource deadlock avoided
33 38 ENAMETOOLONG Filename too long
34 39 ENOLCK No locks available
35 40 ENOSYS Function not implemented
36 41 ENOTEMPTY Directory not empty
37 42 EILSEQ Illegal byte sequence
38 10000 WSABASEERR Unknown error
39 10004 WSAEINTR Unknown error
40 10009 WSAEBADF Unknown error
41 10013 WSAEACCES Unknown error
42 10014 WSAEFAULT Unknown error
43 10022 WSAEINVAL Unknown error
44 10024 WSAEMFILE Unknown error
45 10035 WSAEWOULDBLOCK Unknown error
46 10036 WSAEINPROGRESS Unknown error
47 10037 WSAEALREADY Unknown error
48 10038 WSAENOTSOCK Unknown error
49 10039 WSAEDESTADDRREQ Unknown error
50 10040 WSAEMSGSIZE Unknown error
51 10041 WSAEPROTOTYPE Unknown error
52 10042 WSAENOPROTOOPT Unknown error
53 10043 WSAEPROTONOSUPPORT Unknown error
54 10044 WSAESOCKTNOSUPPORT Unknown error
55 10045 WSAEOPNOTSUPP Unknown error
56 10046 WSAEPFNOSUPPORT Unknown error
57 10047 WSAEAFNOSUPPORT Unknown error
58 10048 WSAEADDRINUSE Unknown error
59 10049 WSAEADDRNOTAVAIL Unknown error
60 10050 WSAENETDOWN Unknown error
61 10051 WSAENETUNREACH Unknown error
62 10052 WSAENETRESET Unknown error
63 10053 WSAECONNABORTED Unknown error
64 10054 WSAECONNRESET Unknown error
65 10055 WSAENOBUFS Unknown error
66 10056 WSAEISCONN Unknown error
67 10057 WSAENOTCONN Unknown error
68 10058 WSAESHUTDOWN Unknown error
69 10059 WSAETOOMANYREFS Unknown error
70 10060 WSAETIMEDOUT Unknown error
71 10061 WSAECONNREFUSED Unknown error
72 10062 WSAELOOP Unknown error
73 10063 WSAENAMETOOLONG Unknown error
74 10064 WSAEHOSTDOWN Unknown error
75 10065 WSAEHOSTUNREACH Unknown error
76 10066 WSAENOTEMPTY Unknown error
77 10067 WSAEPROCLIM Unknown error
78 10068 WSAEUSERS Unknown error
79 10069 WSAEDQUOT Unknown error
80 10070 WSAESTALE Unknown error
81 10071 WSAEREMOTE Unknown error
82 10091 WSASYSNOTREADY Unknown error
83 10092 WSAVERNOTSUPPORTED Unknown error
84 10093 WSANOTINITIALISED Unknown error
85 10101 WSAEDISCON Unknown error

In the above Python command line, you can of course skip the "&& gvim out2" part. It is just there to automatically open the output file in gVim (text editor) after the utility runs.

The above output was from running it with Python 2.
The utility is written to also work with Python 3.
To change the command line to use Python 3, just change 2 to 3 everywhere in the above Python command :)
(You need to install or already have py, the Python Launcher for Windows, for the py command to work. If you don't have it, or are not on Windows, use python instead of py -2 or py -3 in the above python command line - after having set your OS PATH to point to Python 2 or Python 3 as wanted.)

The only differences in the output are the version message (2.x vs 3.x), and the number of error codes - 86 in Python 2 vs. 101 in Python 3.
Unix people will recognize many of the messages (EACCES, ENOENT, EBADF, etc.) as being familiar ones that you get while programming on Unix.
The error names starting with W are probably Windows-specific errors. Not sure how to get the messages for those, need to look it up. (It currently shows "Unknown error" for them.)

This above Python utility was inspired by an earlier auxiliary utility I wrote, called showsyserr.c, as part of my IBM developerWorks article, Developing a Linux command-line utility (not the main utility described in the article). Following (recursively) the link in the previous sentence will lead you to the code for both the auxiliary and the main utility, as well as the PDF version of the article.

Enjoy.

- Vasudev Ram - Online Python training and consulting

Get updates (via Gumroad) on my forthcoming apps and content.

Jump to posts: Python * DLang * xtopdf

Subscribe to my blog by email

My ActiveState Code recipes

Follow me on: LinkedIn * Twitter

Managed WordPress Hosting by FlyWheel



Thứ Sáu, 10 tháng 2, 2017

tp, a simple text pager in Python

By Vasudev Ram

Yesterday I got this idea of writing a simple text file pager in Python.

Here it is, in file tp.py:
'''
tp.py
Purpose: A simple text pager.
Version: 0.1
Platform: Windows-only.
Can be adapted for Unix using tty / termios calls.
Only the use of msvcrt.getch() needs to be changed.
Author: Vasudev Ram
Copyright 2017 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: https://jugad2.blogspot.com
Product store: https://gumroad.com/vasudevram
'''

import sys
import string
from msvcrt import getch

def pager(in_fil=sys.stdin, lines_per_page=10, quit_key='q'):
assert lines_per_page > 1 and lines_per_page == int(lines_per_page)
assert len(quit_key) == 1 and \
quit_key in (string.ascii_letters + string.digits)
lin_ctr = 0
for lin in in_fil:
sys.stdout.write(lin)
lin_ctr += 1
if lin_ctr >= lines_per_page:
c = getch().lower()
if c == quit_key.lower():
break
else:
lin_ctr = 0

def main():
try:
sa, lsa = sys.argv, len(sys.argv)
if lsa == 1:
pager()
elif lsa == 2:
with open(sa[1], "r") as in_fil:
pager(in_fil)
else:
sys.stderr.write
("Only one input file allowed in this version")

except IOError as ioe:
sys.stderr.write("Caught IOError: {}".format(repr(ioe)))
sys.exit(1)

except Exception as e:
sys.stderr.write("Caught Exception: {}".format(repr(e)))
sys.exit(1)

if __name__ == '__main__':
main()
I added a couple of assertions for sanity checking.

The logic of the program is fairly straightforward:

- open (for reading) the filename given as command line argument, or just read (the already-open) sys.stdin
- loop over the lines of the file, lines-per-page lines at a time
- read a character from the keyboard (without waiting for Enter, hence the use of msvcrt.getch [1])
- if it is the quit key, quit, else reset line counter and print another batch of lines
- do error handling as needed

[1] The msvcrt module is on Windows only, but there are ways to get equivalent functionality on Unixen; google for phrases like "reading a keypress on Unix without waiting for Enter", and look up Unix terms like tty, termios, curses, cbreak, etc.

And here are two runs of the program that dogfood it, one directly with a file (the program itself) as a command-line argument, and the other with the program at the end of a pipeline; output is not shown since it is the same as the input file, in both cases; you just have to press some key (other than q (which makes it quit), repeatedly, to page through the content):
$ python tp.py tp.py
$type tp.py | python tp.py

I could have golfed the code a bit, but chose not to, in the interest of the Zen of Python. Heck, Python is already Zen enough.

- Vasudev Ram - Online Python training and consulting

Get updates (via Gumroad) on my forthcoming apps and content.

Jump to posts: Python * DLang * xtopdf

Subscribe to my blog by email

My ActiveState Code recipes

Follow me on: LinkedIn * Twitter

Managed WordPress Hosting by FlyWheel



Thứ Bảy, 12 tháng 11, 2016

Trapping KeyboardInterrupt and EOFError for program cleanup

By Vasudev Ram

Ctrl-C and Ctrl-Z handling

I had written this small Python utility for my own use, to show the ASCII code for any input character typed at the keyboard. Since it was a quick utility, I was initially just using Ctrl-C to exit the program. But that leaves behind a messy traceback, so I thought of trapping the exceptions KeyboardInterrupt (raised by Ctrl-C) and EOFError (raised by Ctrl-Z). With that, the program now exits cleanly on typing either of those keys.

Here is the resulting utility, char_to_ascii_code.py:
from __future__ import print_function
"""
char_to_ascii_code.py
Purpose: Show ASCII code for a given character, interactively,
in a loop. Show trapping of KeyboardInterrupt and EOFError exceptions.
Author: Vasudev Ram
Web site: https://vasudevram.github.io
Blog: https://jugad2.blogspot.com
Product store: https://gumroad.com/vasudevram
"""

print("This program shows the ASCII code for any given ASCII character.")
print("Exit the program by pressing Ctrl-C or Ctrl-Z.")
print()

while True:
try:
c = raw_input( \
"Enter an ASCII character to see its ASCII code: ")
if len(c) != 1:
print("Error: need a string of length 1; retry.")
continue
print("Character:", c)
print("Code:", ord(c))
except KeyboardInterrupt as ki:
print("Caught:", repr(ki))
print("Exiting.")
break
except EOFError as eofe:
print("Caught:", repr(eofe))
print("Exiting.")
break
Here is a sample run, that shows the ASCII codes for the comma, tab and pipe characters, which are commonly used as field delimiters in Delimiter-Separated Value (DSV) files.
$ python char_to_ascii_code.py
This program shows the ASCII code for any given ASCII character.
Exit the program by pressing Ctrl-C or Ctrl-Z.

Enter an ASCII character to see its ASCII code, or Ctrl-C to exit: ,
Character: ,
Code: 44
Enter an ASCII character to see its ASCII code, or Ctrl-C to exit:
Character:
Code: 9
Enter an ASCII character to see its ASCII code, or Ctrl-C to exit: |
Character: |
Code: 124
Enter an ASCII character to see its ASCII code, or Ctrl-C to exit:
Caught: KeyboardInterrupt()
Exiting.
$
I pressed the Ctrl-C key combination to exit the program. Ctrl-C does not show on the screen, but the exception handler for it is activated, and prints the last message above.

Another run shows a few more codes and the trapping of the Ctrl-Z key combination.
$ python char_to_ascii_code.py
This program shows the ASCII code for any given ASCII character.
Exit the program by pressing Ctrl-C or Ctrl-Z.

Enter an ASCII character to see its ASCII code, or Ctrl-C to exit: !
Character: !
Code: 33
Enter an ASCII character to see its ASCII code, or Ctrl-C to exit: ~
Character: ~
Code: 126
Enter an ASCII character to see its ASCII code, or Ctrl-C to exit: ^Z
Caught: EOFError()
Exiting.

- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

Jump to posts: Python   DLang   xtopdf

Subscribe to my blog by email

My ActiveState recipes



Thứ Ba, 4 tháng 10, 2016

Get names and types of a Python module's attributes


By Vasudev Ram



Hi readers,

Today I thought of this simple Python utility while using introspection to look at some modules.

It looks at a module, and for each attribute in it, it tells you the name and type of the attribute. This is useful if you are exploring some new Python module (built-in or third-party), and you want, for example, to know all the functions or methods in it, so that you can further introspect those by printing their docstrings, using the form:
print(module_name.function_or_method_name.__doc__)
because the docstring of a Python function of method, if present, is a nice capsule summary of: its arguments, what it does, and its return value (i.e. its input, processing and output). So with such a docstring, in many cases, a reasonably experienced programmer may not even need to look up the actual Python docs for that function or method, before beginning to use it, thereby saving their time.

So here is the utility:
from __future__ import print_function

# mod_attrs_and_types.py
# Purpose: To show the attribute names and types
# of a Python module, to help with learning about it.
# Author: Vasudev Ram
# Copyright 2016 Vasudev Ram
# Web site: https://vasudevram.github.io
# Blog: http://jugad2.blogspot.com
# Product store: https://gumroad.com/vasudevram

import sys

def attrs_and_types(mod_name):

print('Attributes and their types for module {}:'.format(mod_name))
print()
for num, attr in enumerate(dir(eval(mod_name))):
print("{idx}: {nam:30} {typ}".format(
idx=str(num + 1).rjust(4),
nam=(mod_name + '.' + attr).ljust(30),
typ=type(eval(mod_name + '.' + attr))))

attrs_and_types(sys.__name__)
Running it like this:
$ python mod_attrs_and_types.py > out
gave this output:
Attributes and their types for module sys:

1: sys.__displayhook__ <type 'builtin_function_or_method'>
2: sys.__doc__ <type 'str'>
3: sys.__egginsert <type 'int'>
4: sys.__excepthook__ <type 'builtin_function_or_method'>
5: sys.__name__ <type 'str'>
6: sys.__package__ <type 'NoneType'>
7: sys.__plen <type 'int'>
8: sys.__stderr__ <type 'file'>
9: sys.__stdin__ <type 'file'>
10: sys.__stdout__ <type 'file'>
11: sys._clear_type_cache <type 'builtin_function_or_method'>
12: sys._current_frames <type 'builtin_function_or_method'>
13: sys._getframe <type 'builtin_function_or_method'>
14: sys._mercurial <type 'tuple'>
15: sys.api_version <type 'int'>
16: sys.argv <type 'list'>
17: sys.builtin_module_names <type 'tuple'>
18: sys.byteorder <type 'str'>
19: sys.call_tracing <type 'builtin_function_or_method'>
20: sys.callstats <type 'builtin_function_or_method'>
21: sys.copyright <type 'str'>
22: sys.displayhook <type 'builtin_function_or_method'>
23: sys.dllhandle <type 'int'>
24: sys.dont_write_bytecode <type 'bool'>
25: sys.exc_clear <type 'builtin_function_or_method'>
26: sys.exc_info <type 'builtin_function_or_method'>
27: sys.exc_type <type 'NoneType'>
28: sys.excepthook <type 'builtin_function_or_method'>
29: sys.exec_prefix <type 'str'>
30: sys.executable <type 'str'>
31: sys.exit <type 'builtin_function_or_method'>
32: sys.flags <type 'sys.flags'>
33: sys.float_info <type 'sys.float_info'>
34: sys.float_repr_style <type 'str'>
35: sys.getcheckinterval <type 'builtin_function_or_method'>
36: sys.getdefaultencoding <type 'builtin_function_or_method'>
37: sys.getfilesystemencoding <type 'builtin_function_or_method'>
38: sys.getprofile <type 'builtin_function_or_method'>
39: sys.getrecursionlimit <type 'builtin_function_or_method'>
40: sys.getrefcount <type 'builtin_function_or_method'>
41: sys.getsizeof <type 'builtin_function_or_method'>
42: sys.gettrace <type 'builtin_function_or_method'>
43: sys.getwindowsversion <type 'builtin_function_or_method'>
44: sys.hexversion <type 'int'>
45: sys.long_info <type 'sys.long_info'>
46: sys.maxint <type 'int'>
47: sys.maxsize <type 'int'>
48: sys.maxunicode <type 'int'>
49: sys.meta_path <type 'list'>
50: sys.modules <type 'dict'>
51: sys.path <type 'list'>
52: sys.path_hooks <type 'list'>
53: sys.path_importer_cache <type 'dict'>
54: sys.platform <type 'str'>
55: sys.prefix <type 'str'>
56: sys.py3kwarning <type 'bool'>
57: sys.setcheckinterval <type 'builtin_function_or_method'>
58: sys.setprofile <type 'builtin_function_or_method'>
59: sys.setrecursionlimit <type 'builtin_function_or_method'>
60: sys.settrace <type 'builtin_function_or_method'>
61: sys.stderr <type 'file'>
62: sys.stdin <type 'file'>
63: sys.stdout <type 'file'>
64: sys.subversion <type 'tuple'>
65: sys.version <type 'str'>
66: sys.version_info <type 'sys.version_info'>
67: sys.warnoptions <type 'list'>
68: sys.winver <type 'str'>
There are other ways to do this, such as using the inspect module, but this is an easy way without inspect.

You can (e)grep for the pattern 'function|method' in the output, to get only the lines you want:

(If you haven't earlier, also check min_fgrep: minimal fgrep command in D.)
$ grep -E "function|method" out
1: sys.__displayhook__             <type 'builtin_function_or_method'>
4: sys.__excepthook__ <type 'builtin_function_or_method'>
11: sys._clear_type_cache <type 'builtin_function_or_method'>
12: sys._current_frames <type 'builtin_function_or_method'>
13: sys._getframe <type 'builtin_function_or_method'>
19: sys.call_tracing <type 'builtin_function_or_method'>
20: sys.callstats <type 'builtin_function_or_method'>
22: sys.displayhook <type 'builtin_function_or_method'>
25: sys.exc_clear <type 'builtin_function_or_method'>
26: sys.exc_info <type 'builtin_function_or_method'>
28: sys.excepthook <type 'builtin_function_or_method'>
31: sys.exit <type 'builtin_function_or_method'>
35: sys.getcheckinterval <type 'builtin_function_or_method'>
36: sys.getdefaultencoding <type 'builtin_function_or_method'>
37: sys.getfilesystemencoding <type 'builtin_function_or_method'>
38: sys.getprofile <type 'builtin_function_or_method'>
39: sys.getrecursionlimit <type 'builtin_function_or_method'>
40: sys.getrefcount <type 'builtin_function_or_method'>
41: sys.getsizeof <type 'builtin_function_or_method'>
42: sys.gettrace <type 'builtin_function_or_method'>
43: sys.getwindowsversion <type 'builtin_function_or_method'>
57: sys.setcheckinterval <type 'builtin_function_or_method'>
58: sys.setprofile <type 'builtin_function_or_method'>
59: sys.setrecursionlimit <type 'builtin_function_or_method'>
60: sys.settrace <type 'builtin_function_or_method'>
You can also (e)grep for a pattern or for alternative patterns:
$ grep -E "std(in|out)" out
9: sys.__stdin__ <type 'file'>
10: sys.__stdout__ <type 'file'>
62: sys.stdin <type 'file'>
63: sys.stdout <type 'file'>

The image at the top of the post is of a replica of a burning glass owned by Joseph Priestley, in his laboratory. If you don't remember your school physics, he is credited with having discovered oxygen.

- Enjoy.

- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

Jump to posts: Python   DLang   xtopdf

Subscribe to my blog by email

My ActiveState recipes

Managed WordPress Hosting by FlyWheel



Thứ Năm, 1 tháng 9, 2016

Quick-and-dirty drive detector in Python (Windows)

By Vasudev Ram

While using Python's os.path module in a project, I got the idea of using it to do a quick-and-dirty check for what drives exist on a Windows system. Actually, not really the physical drives, but the drive letters, that may in reality be mapped any of the following: physical hard disk drives or logical partitions of them, CD or DVD drives, USB drives, or network-mapped drives.

The script, drives.py (below), has two functions, drives() and drives2(). The drives() function prints the required information. The drives2() function is more modular and hence more reusable, since it returns a list of detected drive letters; in fact, drives() can be implemented in terms of drives2().
from __future__ import print_function

'''
Author: Vasudev Ram
Copyright 2016 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: http://jugad2.blogspot.com
Product store: http://gumroad.com/vasudevram
'''

from os.path import exists

def drives():
# Limit of 'N' chosen arbitrarily.
# For letters in the first half of the alphabet:
for drive in range(ord('A'), ord('N')):
print('Drive', chr(drive), 'exists:', exists(chr(drive) + ':'))

print()

drives()

print()

def drives2():
drive_list = []
for drive in range(ord('A'), ord('N')):
if exists(chr(drive) + ':'):
drive_list.append(chr(drive))
return drive_list

print("The following drives exist:", drives2())
I ran it thusly:
$ python drives.py
And the output was thisly:
Drive A exists: False
Drive B exists: False
Drive C exists: True
Drive D exists: True
Drive E exists: True
Drive F exists: False
Drive G exists: False
Drive H exists: True
Drive I exists: False
Drive J exists: False
Drive K exists: False
Drive L exists: False
Drive M exists: False

The following drives exist: ['C', 'D', 'E', 'H']

As we can see, the program relies on the fact that a drive specification like "C:" is considered as a path on Windows, since it means "the current directory on drive C". That is why os.path.exists() works for this use. The program does not use a real OS API that returns information about available drives.

I have only tested it a few times, on my machine. It could be that in other tests, or on other machines, it may fail for some reason, such as a drive that is present but inaccessible for some reason (permissions, hardware issue or other). If you try it and get any errors, I'd be interested to know the details - please leave a comment. Thanks.

- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

Jump to posts: Python   DLang   xtopdf

Subscribe to my blog by email

My ActiveState recipes