Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python tool for incorporating imported items

Is there a tool in python to rewrite some code which imports things such that it no longer has to import anything?

Take a library that draws a box called box.py

def box(text='Hello, World!')
    draw the box magic
    return

Now in another program (we'll call it warning.py) it says:

from box import box

box('Warning, water found in hard drive')

Is there a tool that I can use that will see it importing the box function (or a class for that matter) from box and insert that function (or class, or even variable definitions) into the warning.py script removing the import line (thus making it more portable)?

With thanks, Narnie

like image 379
narnie Avatar asked Apr 21 '26 20:04

narnie


1 Answers

It sounds like you're wanting to effectively copy-paste everything into one file to be able to distribute a single file instead of several?

In that case, look into using a zipped module instead of copy-pasting everything into one file... This is far more maintainable in the long run.

Python will execute a zip file if there's a __main__.py file inside of it.

E.g.:

echo "def foo(): print 'code inside a.py'" > a.py
echo "def bar(): print 'code inside b.py'" > b.py
echo "import a; import b; a.foo(); b.bar()" > __main__.py
zip test.zip a.py b.py __main__.py
rm a.py b.py __main__.py

python test.zip

This creates a zip file with 3 python files inside of it. It can be executed with python test.zip. Everything is completely self-contained. (I believe this requires python >= 2.6, by the way...)

like image 161
Joe Kington Avatar answered Apr 24 '26 10:04

Joe Kington