Showing posts with label Python-one-liners. Show all posts
Showing posts with label Python-one-liners. Show all posts

Saturday, December 29, 2018

The Zen of Python is well sed :)


Image


- By Vasudev Ram - Online Python training / SQL training / Linux training

$ python -c "import this" | sed -n "4,4p;15,16p"
Explicit is better than implicit.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.


- Vasudev Ram - Online Python training and consulting

I conduct online courses on Python programming, Unix / Linux commands and shell scripting and SQL programming and database design, with course material and personal coaching sessions.

The course details and testimonials are here.

Contact me for details of course content, terms and schedule.

Or if you're a self-starter, check out my Python programming course by email.

Try FreshBooks: Create and send professional looking invoices in less than 30 seconds.

Learning Linux? Hit the ground running with my vi quickstart tutorial.

Sell your digital products via DPD: Digital Publishing for Ebooks and Downloads.

Posts about: Python * DLang * xtopdf

My ActiveState Code recipes

Follow me on:


Friday, February 3, 2017

Time to Upgrade Your Python: TLS v1.2 Will Soon Be Mandatory (pyfound.blogspot.com)

By Vasudev Ram

Saw this blog post recently via an email from the PSF (Python Software Foundation):

Time to Upgrade Your Python: TLS v1.2 Will Soon Be Mandatory

and then also saw this HN thread (about the same post):

Time to Upgrade Your Python: TLS v1.2 Will Soon Be Mandatory (pyfound.blogspot.com)

The currently top comment in that thread, (by HN user jwilk), had examples of how to do the check for your Python's TLS version - for both Py 2 and Py 3, without using the 3rd-party requests library (which was used in the PSF post), just using Python's urllib* libraries:

From jwilk's comment:

Test procedure that doesn't require 3rd-party libs:
* For Python 2:
$ python -c "import json, urllib2; print json.load(urllib2.urlopen('https://www.howsmyssl.com/a/check'))['tls_version']"
* For Python 3:
$ python3 -c "import json, urllib.request; print(json.loads(urllib.request.urlopen('https://www.howsmyssl.com/a/check').read().decode('UTF-8'))['tls_version'])"

Tried them both out on my machine, they worked and showed the TLS version.

Speaking of one-liners, here are a few of my own, some by others, and in both Python and Unix:

Python one-liner to get the filename and line number of the caller of the current function

Python one-liner to compare two files (conditions apply)

Python one-liner to open a web site from the command line

And you can always get all the Python one-liners on my blog, both past and future [1], with this URL:

https://jugad2.blogspot.in/search/label/Python-one-liners

[1] Future one-liners, after they are written, not now :)

And the same for general one-liners (could include Python, Unix or other):

https://jugad2.blogspot.in/search/label/one-liners

- 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



Tuesday, March 29, 2016

Python one-liner to compare two files (conditions apply)

By Vasudev Ram

In my previous post a couple of days back:

A basic file compare utility in Python

I said that it was possible to write a shorter version of this program, subject to certain limitations.

You can do it with a one-liner. The limitation is that the sum of the sizes of both files being compared should be less than your computer's free memory [1]. This because I read both files fully into memory [2] to compare them [3].

First, the input files, 3 of the same ones as in the previous post I linked to above.
$ type f0.txt
file 1

$ type f1.txt
file 1

$ type f2.txt
file 2
And here is the Python one-liner, run on a pair of identical files and then on a pair of differing files:
$  python -c "print open('f0.txt', 'rb').read() == open('f1.txt', 'rb').read()"
True

$  python -c "print open('f0.txt', 'rb').read() == open('f2.txt', 'rb').read()"
False
Voila!

Note that you have to use the file opening mode of 'rb' (for 'read' and 'binary'), not just 'r', because otherwise Python will do newline translation and your result can be wrong, at least on Windows. I actually had this happen and then corrected the script.

[1] The free memory is what is left after subtracting from your total RAM, the space taken by the OS, buffer cache, other running apps and their data, the Python interpreter, and your script. So if you have 4 GB RAM, and the sum of the megabytes used by those items is 2.4 MB, you have 1.6 MB free, so the total size of files you can compare, if they are of equal size, is two files of 0.8 MB each. [4]

[2] Perl people call this technique slurping a file, and use it a lot. when feasible.

[3] Of course, with this technique we lose the extra info that the original program (file_compare.py) gives us, such as why the input files differ (e.g. in size or content).

[4] Not being 100% precise here, because Python data structures have some overhead. See the sys.getsizeof() function.

If you like one-liners, here are some more, some by me, some by others:

UNIX one-liner to kill a hanging Firefox process
(This one has some interesting comments on Unix processes.)

Python one-liner to open a web site from the command line

A first Python one-liner

Multiple Python one-liners

Python one-liner to get the filename and line number of the caller of the current function

- Vasudev Ram - Online Python training and programming

Signup to hear about new products and services I create.

Posts about Python  Posts about xtopdf

My ActiveState recipes

Wednesday, November 26, 2014

A first Python one-liner

By Vasudev Ram

1. Install Python 2.7 (if you don't have it already).

2. Run this at the command line:

python -c "print ''.join(list(reversed('!dlrow olleH')))"

- Vasudev Ram - Dancing Bison Enterprises

Contact Page

Friday, November 1, 2013

Python one-liner to open a web site from the command line


By Vasudev Ram

Image

While importing the antigravity module, I came up with this Python one-liner to open a web site from the command line:

import sys, os.path, webbrowser; webbrowser.open("http://" + os.path.splitext(os.path.basename(sys.argv[0]))[0])

If you save the above Python code as, say, a.site.com.py, you can run it from the command line with:
C:> a.site.com.py

where a.site.com could be any existing site, like ibm.com, oreilly.com, python.org, mit.edu, etc. (You have to add the extension .py to the site name to create the file name.)

This should open that web site in your default web browser.

To do the same for other sites, just copy, for example, ibm.com.py to python.org.py .

The content of the file does not need to be edited for different sites, since there is no hard-coding of the site name in the code, only in the file name.

Though I haven't tested this on UNIX or Linux yet, you should be able to make a link from the first site filename to any number of others (one at a time), and achieve the same result as the copy on Windows. The command would be of the form:

$ ln ibm.com.py python.org.py

I also haven't tried the one-liner on UNIX or Linux (yet), but it is likely to work, since the webbrowser module of Python that it uses, is supposed to work there too. But check.

If you like one-liners, you may also find this one (which I wrote a while ago) interesting:

UNIX one-liner to kill a hanging Firefox process

(The comments on that one are also interesting and go into some detail on UNIX processes.)

- Vasudev Ram - Dancing Bison Enterprises

Consulting / training inquiry




DiscountMags.com


Tuesday, June 4, 2013

Multiple Python one-liners

Notes from MPUG, June 2013: “Python one-liners” talk | Curious Venn

Saw this today, interesting and useful.

The page linked above also has links to other pages with more such Python one-liners, including a discussion on StackOverflow.

Many of the Python one-liners shown, use the "python -m" technique, but that's not all there is to it - some of those also show innovative or non-intuitive uses of that technique.

Two of my favorites from the one-liners shown, are the 'e' module on PyPI :-), and the use of the gzip or zip modules on the command-line as a substitute when you don't have access to a native (un)zip or g(un)zip binary/executable, but do have Python available. "Batteries included" wins here.

You can also run simple Internet servers or clients for HTTP, FTP, POP, SMTP, telnet, etc., using the -m option of Python.

These uses of Python one-liners for Internet purposes reminds me of the REBOL language, in which you can also do such things:

http://jugad2.blogspot.com/2012/12/rebol-language-that-influenced-json-is.html

Update: I saw the MPUG Python talk (linked above) via Hacker News, here:

https://news.ycombinator.com/item?id=5814165

and then wrote this post. Just after writing my post, I visited Planet Python and saw that the MPUG post, by Graeme Cross (curiousvenn.com) was already on the planet.

Anyway, I'm not deleting my post.

Update 2: The HN thread also mentions this other list of one-liners on the Python Wiki:

http://wiki.python.org/moin/Powerful%20Python%20One-Liners

(some good ones there too), and that list also mentions PyP, a Python tool by Sony ImageWorks to create hjgh-performance image-processing pipelines. I had  blogged about PyP and related Python pipe tools some time ago, and those tools were what gave me the idea to create my pipe_controller project:

http://jugad2.blogspot.in/2011/09/some-ways-of-doing-unix-style-pipes-in.html

http://jugad2.blogspot.in/2012/08/pipecontroller-v01-released-simulating.html

http://jugad2.blogspot.com/2012/09/using-pipecontroller-to-run-pipe.html

http://jugad2.blogspot.com/2012/10/swapping-pipe-components-at-runtime.html

https://bitbucket.org/vasudevram/pipe_controller

- Vasudev Ram
dancingbison.com

Wednesday, March 13, 2013

Python one-liner to get the filename and line number of the caller of the current function

By Vasudev Ram

Just saw this:

An ActiveState Python recipe to get the filename and line number of the calling function.

I modified it and tried it out, while I happened to be at an Internet cafe, using Portable Python, which I had blogged about earlier.

Here is my modified code:
# caller_info.py

import sys

def foo():
 print "in foo"
 f1 = sys._getframe(1)
 f2 = sys._getframe(2)
 print "f1: filename, lineno:", f1.f_code.co_filename, f1.f_lineno
 print "f2: filename, lineno:", f2.f_code.co_filename, f2.f_lineno

def bar():
 print "in bar"
 print "calling foo"
 foo()

bar()

And here is the output of "running" (*) that file, caller_info.py, using Portable Python:

>>> import caller_info
in bar
calling foo
in foo
f1: filename, lineno: caller_info.py 16
f2: filename, lineno: caller_info.py 18
>>>
(*) I said "running" because, as you can see from the code, I had to use a roundabout method of running the caller_info.py file with PortablePython. The standard method, like "python caller_info.py", that normal Python supports, does not seem to work with PortablePython (at least on a quick check or two; there may be some other way that works, such as a command-line switch or whatever). So I resorted to importing the file and letting the code in it run as a side-effect. Anyway, it seems to show that the one-liner works, because in the output shown, the filename is right, and so are the line numbers of the calls to foo and bar - I checked in the editor that the numbers are 16 and 18.

Just for fun, I also tried the same code (not as a Python file, just typed in), in the
repl.it online pastebin that I blogged about earlier. It worked, sort of, the line number shown was 1 and the filename shown was stdin:
def foo(): 
..   print "in foo" 
..
 def bar(): 
..   print "in bar, calling foo" 
..   foo() 
..   f = sys._getframe(1) 
..   print f.f_code.co_filename 
..   print f.f_lineno 
..   
   bar()
in bar, calling foo
in foo
<stdin>
1
- Vasudev Ram - Dancing Bison Enterprises