简体   繁体   中英

How can virtualenv create different python environments?

My server has 3 virtualenv scripts:

$ ls -lt virtual*
lrwxrwxrwx 1 root root  4 Nov 22 06:19 virtualbox -> VBox
-rwxr-xr-x 2 root root 55 Aug 14 19:34 virtualenv
-rwxr-xr-x 1 root root 55 Aug 14 19:34 virtualenv2
-rwxr-xr-x 2 root root 55 Aug 14 19:34 virtualenv3
$ cat virtualenv
#!/usr/bin/python3
import virtualenv
virtualenv.main()
$ cat virtualenv2
#!/usr/bin/python2
import virtualenv
virtualenv.main()
$ cat virtualenv3
#!/usr/bin/python3
import virtualenv
virtualenv.main()

I know virtualenv2 is used to create Python 2 environment while virtualenv3 is for Python 3 . But what confuses me is why just modify the /usr/bin/python2 to /usr/bin/python3 in shebang line can achieve the effect that create different environments? What is the magic behind it?

There are two pieces of "magic".

1) The shebang line informs the kernel of the correct interpreter to use. When you invoke virtualenv2 , the kernel expands that to /usr/bin/python2 virtualenv2 . Similarly, when you invoke vitualenv3 , the kernel expands that to /usr/bin/python3 virtualenv3 .

2) The virtualenv.main() creates a virtual environment based upon the currently running interpreter. For example, if virtualenv.main() is invoked by /usr/bin/python3 , then it creates a virtual environment based upon /usr/bin/python3 .

Hopefully you can see that these two "magic" items, taken together, perform the intended action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM