[issue41256] activate script created by venv is not smart enough

Jack DeVries report at bugs.python.org
Fri Jul 23 14:16:58 EDT 2021


Jack DeVries <jdevries3133 at gmail.com> added the comment:

What do you think about this as an entrypoint?

```sh
#!/usr/bin/env

# this becomes venv/bin/activate
# the old venv/bin/activate is now venv/bin/activate.sh

# Try to execute a `return` statement,
# but do it in a sub-shell and catch the results.
# If this script isn't sourced, that will raise an error.
$(return >/dev/null 2>&1)

# What exit code did that give?
if [ "$?" -ne "0" ]
then
    echo "Warning: this script must be sourced, not run in a subshell."
    echo "Try \"source /path/to/activate\" on unix-like systems."
fi

# dispatch to shell-specific activate scripts
# *ignore proper path construction for the sake of demonstration...*
[ $BASH_VERSION ] || [ $ZSH_VERSION ] && . ./activate.sh
[ $FISH_VERSION ] && . ./activate.fish
[ $csh_version ] && . ./activate.csh
```

The try-to-return trick was shamelessly taken from here:
https://stackoverflow.com/a/34642589/13262536

I am a shell scripting novice, so I am certain that there are many unaddressed edge cases here. I know that reliably detecting whether a script has been sourced or "ran" is essentially impossible to do in a cross-platform way.

----------
nosy: +jack__d

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41256>
_______________________________________


More information about the Python-bugs-list mailing list