diff --git a/.hgignore b/.hgignore
--- a/.hgignore
+++ b/.hgignore
@@ -39,6 +39,7 @@
 doc/*.[0-9].txt
 doc/*.[0-9].gendoc.txt
 doc/*.[0-9].{x,ht}ml
+hg
 MANIFEST
 MANIFEST.in
 patches
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -46,7 +46,11 @@
 
 all: build doc
 
-local:
+hg: hg.in.py
+	$(PYTHON) -c "import sys; sys.stdout.write(sys.stdin.read().replace('%(interpreter)s', sys.executable))" < hg.in.py > hg
+	chmod +x hg
+
+local: hg
 	$(PYTHON) setup.py $(PURE) \
 	  build_py -c -d . \
 	  build_ext $(COMPILERFLAG) -i \
@@ -54,10 +58,10 @@
 	  build_mo
 	env HGRCPATH= $(PYTHON) hg version
 
-build:
+build: hg
 	$(PYTHON) setup.py $(PURE) build $(COMPILERFLAG)
 
-wheel:
+wheel: hg
 	FORCE_SETUPTOOLS=1 $(PYTHON) setup.py $(PURE) bdist_wheel $(COMPILERFLAG)
 
 doc:
@@ -75,6 +79,7 @@
 	$(MAKE) -C contrib/chg distclean
 	rm -rf rust/target
 	rm -f mercurial/rustext.so
+	rm -f hg
 
 clean: cleanbutpackages
 	rm -rf packages
@@ -110,17 +115,17 @@
 
 check: tests
 
-tests:
+tests: hg
         # Run Rust tests if cargo is installed
 	if command -v $(CARGO) >/dev/null 2>&1; then \
 		cd $(HGROOT)/rust/hg-cpython && $(CARGO) test --quiet --all; \
 	fi
 	cd tests && $(PYTHON) run-tests.py $(TESTFLAGS)
 
-test-%:
+test-%: hg
 	cd tests && $(PYTHON) run-tests.py $(TESTFLAGS) $@
 
-testpy-%:
+testpy-%: hg
 	@echo Looking for Python $* in $(HGPYTHONS)
 	[ -e $(HGPYTHONS)/$*/bin/python ] || ( \
 	cd $$(mktemp --directory --tmpdir) && \
@@ -204,10 +209,10 @@
   ppa
 
 # Forward packaging targets for convenience.
-$(packaging_targets):
+$(packaging_targets): hg
 	$(MAKE) -C contrib/packaging $@
 
-osx:
+osx: hg
 	rm -rf build/mercurial
 	/usr/bin/python2.7 setup.py install --optimize=1 \
 	  --root=build/mercurial/ --prefix=/usr/local/ \
diff --git a/hg b/hg.in.py
old mode 100755
new mode 100644
rename from hg
rename to hg.in.py
--- a/hg
+++ b/hg.in.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!%(interpreter)s
 #
 # mercurial - scalable distributed SCM
 #
diff --git a/tests/test-check-code.t b/tests/test-check-code.t
--- a/tests/test-check-code.t
+++ b/tests/test-check-code.t
@@ -62,7 +62,7 @@
   COPYING
   Makefile
   README.rst
-  hg
+  hg.in.py
   hgeditor
   hgweb.cgi
   setup.py