Using bash to source a python environment

248 views
Skip to first unread message

Corina Tudorache

unread,
Jun 16, 2017, 8:45:56 AM6/16/17
to golang-nuts
Hi. I am trying to source a python environment in go. I run this command:cmd := exec.Command("/bin/sh", "-c", ". /path to python environment/bin/activate"), but actually yhe environment is not activated. I don't know what I am missing. Any tip is much appreciated. :)

Lutz Horn

unread,
Jun 16, 2017, 9:09:25 AM6/16/17
to golan...@googlegroups.com
Hi,

> cmd := exec.Command("/bin/sh", "-c", ". /path to python
> environment/bin/activate")
> but actually yhe environment is not activated

How do you check this? What do you want to do *after* this call to
exec.Command?

Lutz

Shawn Milochik

unread,
Jun 16, 2017, 10:03:38 AM6/16/17
to golang-nuts
Even if successful, it happens in a subprocess that your exec.Cmd creates. It will not affect your own shell session. If you are trying to run a Python script with exec.Cmd, you can just do that directly:

cmd := exec.Cmd("/path/to/virtualenv/bin/python", "/path/to/your/code.py")

Alternatively, you can just put ["PATH=/path/to/your/virtualenv/bin"] in your exec.Cmd's "Env" slice, which is pretty much all virtualenv's "activate" script does, then exec.Command("/path/to/your/script.py") (assuming your script is executable).

If you want to have a Go program make changes to your interactive shell session, you'd have to connect your exec.Cmd's Stdout, Stderr, and Stdin to os.Stdout, os.Stderr, and os.Stdin an run your Go command as a "middleman" between your session and your exec.Cmd session.

Finally, if you really really want to run a Go program and make changes to your environment after your Go program exits, you're going to have to do some clever things with your bash profile. I don't know how it works, but this project accomplishes it: https://github.com/direnv/direnv

Fun fact: If you store Python code in your Go program (as a raw string), you can create a command with exec.Command("/path/to/your/virtualenv/bin/python") and feed the string into your cmd.Stdin. Same for bash, Perl, and whatever happens to be installed on your machine. ^_^


Reply all
Reply to author
Forward
0 new messages