Oscar Benjamin wrote:

> On 28 April 2016 at 02:02, Kanika Murarka <murarkakan...@gmail.com> wrote:
>> Thanks Oliver and Alex, I didnt know about these commands :D
>>
>> Oliver,
>> When i typed
>>                 print filename
>>                 print sys.executable
>>                 print sys.prefix
>>                 print os.path.split(sys.prefix)[-1]
>>
>> my output was
>>
>> /home/kanikaa/pydsa7/venv/lib/python2.7/site-
packages/ipython_genutils/tests/test_tempdir.py
>>                 /usr/bin/python
>>                 /usr
>>                 usr
>> but i want to know weather file belongs to 'venv' folder or not.
> 
> You can check if the 'venv' folder is part of a path using:
> 
> import os.path
> 
> dirpath = os.path.dirname(filename)
> dirnames = []
> while dirpath:
>     dirpath, dirname = os.path.split(dirpath)
>     dirnames.append(dirname)
> 
> if 'venv' in dirnames:
>     # do whatever
> 
> But how would you know that 'venv' is the name of a virtual
> environment folder? A virtual environment folder can be called
> anything.
> 
> You can write some code to test if a particular path represents the
> base directory of a virtual environment but I expect it would probably
> be fragile. Without knowing why you want to do this I suggest that you
> might want to find a different general approach to your real problem.

You could look for bin/activate. Yes, it's fragile, but in practice it might 
be good enough:

import pathlib
import sys

path = sys.argv[1]

for p in pathlib.Path(path).parents:
    if p.joinpath("bin/activate").is_file():
        print("potential virtual environment:")
        print(p)
        break


$ python3 check_venv.py /home/nemo/virt/docopt/lib/python2.7/site-
packages/docopt.py
potential virtual environment:
/home/nemo/virt/docopt


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to