0

I have two Python scripts

  • 2011/2/dinner/dinner.py
  • 2014/qualification/cookie-clicker-alpha/cookie-clicker-alpha.py

They both define identical functions binary_search. For maintainability, I would like to move that function to a new file

  • helpers/binary_search.py

Then import it from dinner.py and cookie-clicker-alpha.py. How can I do that? I am using Python 3.x .

Finally, it's important to me that python dinner.py still works out the box for anyone who clones my code:

git clone https://github.com/hickford/codejam.git
cd codejam
cd 2011/2/dinner
python dinner.py sample.in
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
  • Is the directory in which `binary_search.py` resides in `sys.path`? – anon582847382 Apr 14 '14 at 18:57
  • Nope. I could put that in the readme, but I think it would be better if people could run the code out the (git clone) box without having to edit their environment variables. – Colonel Panic Apr 14 '14 at 18:58
  • If you care about other people downloading and installing your code, you'll ultimately want to create an egg-based `setuptools` distribution, and release versions of it to [PyPi](https://pypi.python.org/pypi). I outlined the basic process I use in [this answer](http://stackoverflow.com/questions/19876993/python-module-import-relative-paths-issue), this might be helpful for you as a starting point. – Lukas Graf Apr 14 '14 at 19:04
  • or maybe try moving on to python [wheels](http://pythonwheels.com/) which is the new standard! – msvalkon Apr 14 '14 at 19:07
  • Typically you put `__init__.py` in the intermediate directories, I thought. So you are missing several `__init__.py`s. – 2rs2ts Apr 14 '14 at 19:13
  • Incidentally, Python has a binary search implementation in the standard library; it's in the `bisect` module. – nneonneo Apr 14 '14 at 19:20

1 Answers1

0

Probably the easiest solution would be to make a symbolic link helpers/binary_search.py in both 2011/2/dinner/ and 2014/qualification/cookie-clicker-alpha/. Then scripts in both directories can just import binary_search.

Another trick to make a couple of modules into one "script" is to zip them;

cd 2011/2/dinner
mkdir tmp
cd tmp
cp ../dinner.py __main__.py
cp ../../../helpers/binary_search.py .
zip ../foo.zip *.py
cd ..
echo '#!/usr/bin/env python' >dinner
cat foo.zip >>dinner
chmod a+x dinner
rm -rf foo.zip tmp/

When the "dinner" program is run, it will unpack the zipped modules and run __main__.py. I've used this with python2, but not with python3.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94