Running Django manage.py commands from anywhere06 May · by Tim Kamanin · 2 min read
One of the most annoying aspects of developing in Django for me is running
manage.py commands: you need to be in the same directory with manage.py
file in order to run a command. This is not convenient. I thought it would be
cool to be able to run manage.py from anywhere in the project as much as you
git command from anywhere within a git project.
The solution is simple: create a bash script that accepts manage.py arguments, takes your current directory and searches for manage.py file in that directory recursivelly and then if file not found there, find goes up a directory and up and up until it finds nearest manage.py or hits the root ('/'). When it finds manage.py it executes it with arguments passed to the bash script. Simple idea, let's implement:
#!/bin/bash managepy_path=0 while [[ "`pwd`" != '/' ]]; do managepy_path=$(find $(pwd) -type f -name "manage.py" -print | head -n 1) if [[ -n $managepy_path ]]; then echo "Running 'python $managepy_path $@' command:" python $managepy_path $@ break else cd .. fi done if [[ managepy_path == 0 ]]; then echo 'Cant find manage.py' fi
Save it to your local bin: /usr/local/bin as manage.py (yes, this is not python file, but it has .py extension to make it sound as vanilla Django manage.py file, you can name it anything you want actually).
And then run it from somewhere deep in your Django project:
And you'll get the output of the nearest manage.py command executed within your currently activated virtualenv or default python environment.
I added the script to its very own git repo at https://github.com/timonweb/Django-manage.py-anywhere and you can now use pip to install the package:
pip install django_managepy_anywhere
Enjoy and let me know how it works for you :)