On Mon, Apr 18, 2016 at 10:12 AM, Nick Coghlan
On 18 April 2016 at 05:28, Koos Zevenhoven
wrote: So here's oneline.py:
https://gist.github.com/k7hoven/21c5532ce19b306b08bb4e82cfe5a609
Neat, although you'll want to use importlib.import_module() rather than calling __import__ directly (the latter won't behave the way you want when importing submodules, as it returns the top level module for the import statement to bind in the current namespace, rather than the imported submodule)
Thanks :). That is in fact why I had worked around it by grabbing sys.modules[name] instead. Good to know import_module() already does the right thing. I now changed the code to use import_module, assuming that is the preferred way today. However, to prevent infinite recursion when importing submodules, I now do a setattr(parentmodule, submodulename, None) before the import (and delattr if the import fails).
I suppose this could be on pypi, and one could do things like
oneline.py "random.randint(0,10)"
or
python -m oneline "random.randint(0,10)"
Any thoughts?
There are certainly plenty of opportunities to make Python easier to invoke for one-off commands. Another interesting example is pyp: https://code.google.com/archive/p/pyp/wikis/pyp_manual.wiki
This is nice, although solves a different problem.
A completely undocumented hack I put together while playing one day was a utility to do json -> json transformations via command line pipes: https://bitbucket.org/ncoghlan/misc/src/default/pycall
So it looks like it would work like this: cat input.json | pycall "my.transformation.function" > output.json Also a different problem, but cool.
The challenge with these kinds of things is getting them from "Hey, look at this cool thing you can do" to "This will materially improve your day-to-day programming experience". The former can still be fun to work on as a hobby, but it's the latter that people need to get over the initial adoption barrier.
I think the users of oneline.py could be people that now write lots of bash scripts and work on the command line. So whenever someone asks a question somewhere about how to do X on the linux command line, we might have the answer: """ Q: On the linux commandline, how do I get only the filename from a full path that is in $FILEPATH A: Python has this. You can use the tools in os.path: Filename: $ oneline.py "os.path.basename('$FILEPATH')" Path to directory: $ oneline.py "os.path.dirname('$FILEPATH')" """ This might be more appealing than python -c. The whole point is to make Python's power available and visible for a larger audience. -Koos