1

I have a Python 3 script that I'm developing on a Linux machine (Ubuntu), but that will be deployed on an embedded Linux device.

On my development machine my required packages are installed in a "virtual environment", but on the embedded device the packages are installed globally. There are no virtual environments on the device, because it is designed to run this one script only.

I'm having trouble with what shebang I should put on top of my script.


According to the answer to this question, the shebang for a script to be run in a virtual environment should be:

#!/usr/bin/env python

But to run the script with Python 3, the shebang should be:

#!/usr/bin/python3

The problem is if I use the first of these shebangs, the script runs on my development machine but does not run when deployed. On the embedded device, it tries to run using Python 2 and fails. When I use the second shebang, the script runs on the embedded device but not on my development machine, since it's not using Python 3 from the virtual environment.

Is there a shebang I can use that will work in both cases: with and without a virtual environment?

Yes, I realize I can just run my script as python3 my_script.py and the shebang won't matter. If I can't get one shebang to work in both cases I guess that's what I'll have to do.

gfrung4
  • 1,658
  • 3
  • 14
  • 22
  • How about just "#!/usr/bin/env python3"? That's what I use. In a virtualenv, you get both python executable names linked into the environment: "python" & "python3" – Mark A Oct 10 '19 at 16:20
  • @MarkA Brilliant! I thought I tried that, but I guess I didn't because I thought anything with `/usr/bin/env` wouldn't work without a virtual environment. If you want to add that as an answer to this question, I would accept it. – gfrung4 Oct 10 '19 at 17:15

1 Answers1

1

You're close. You can use python3 because a link to both python and python3 will be created inside the virtualenv's bin directory.

Just this will do it:

#!/usr/bin/env python3

...
Mark A
  • 838
  • 5
  • 8