11import errno
22import subprocess
3+ import sys
34
45from django .db import connections
56from django .core .management .commands import dbshell
@@ -21,15 +22,41 @@ def handle(self, **options):
2122 getattr (self , cmd )(connection )
2223 return
2324 except OSError , e :
24- if e .errno != errno .ENOENT :
25- self .stderr .write ("Could not start %s: %s" % (cmd , str (e )))
25+ if self ._is_virtualenv :
26+ # retry without explicitly without virtualenv
27+ try :
28+ getattr (self , cmd )(connection , ignore_virtualenv = True )
29+ return
30+ except OSError , e :
31+ if e .errno != errno .ENOENT :
32+ self .stderr .write ("Could not start %s: %s" % (cmd , str (e )))
33+ else :
34+ if e .errno != errno .ENOENT :
35+ self .stderr .write ("Could not start %s: %s" % (cmd , str (e )))
2636
2737 super (Command , self ).handle (** options )
2838
29- def pgcli (self , connection ):
39+ @property
40+ def _is_virtualenv (self ):
41+ # sys.real_prefix is only set if inside virtualenv
42+ return hasattr (sys , 'real_prefix' )
43+
44+ @property
45+ def _python_path (self ):
46+ path = '{}/bin/' .format (sys .prefix ) if self ._is_virtualenv else ''
47+ return path
48+
49+ def _get_cli_command (self , cli , ignore_virtualenv = False ):
50+ cli_command = '{}{}' .format (
51+ '' if ignore_virtualenv else self ._python_path ,
52+ cli , # 'pgcli' or 'mycli'
53+ )
54+ return cli_command
55+
56+ def pgcli (self , connection , ignore_virtualenv = False ):
3057 # argument code copied from Django
3158 settings_dict = connection .settings_dict
32- args = ['pgcli' ]
59+ args = [self . _get_cli_command ( 'pgcli' , ignore_virtualenv = ignore_virtualenv ) ]
3360 if settings_dict ['USER' ]:
3461 args += ["-U" , settings_dict ['USER' ]]
3562 if settings_dict ['HOST' ]:
@@ -40,10 +67,10 @@ def pgcli(self, connection):
4067
4168 subprocess .call (args )
4269
43- def mycli (self , connection ):
70+ def mycli (self , connection , ignore_virtualenv = False ):
4471 # argument code copied from Django
4572 settings_dict = connection .settings_dict
46- args = ['mycli' ]
73+ args = [self . _get_cli_command ( 'mycli' , ignore_virtualenv = ignore_virtualenv ) ]
4774 db = settings_dict ['OPTIONS' ].get ('db' , settings_dict ['NAME' ])
4875 user = settings_dict ['OPTIONS' ].get ('user' , settings_dict ['USER' ])
4976 passwd = settings_dict ['OPTIONS' ].get ('passwd' , settings_dict ['PASSWORD' ])
0 commit comments