I'm currently writing a shell script using Python 2.7. To install virtual-env I am using the following:
def setup_virtal_env(package):
try:
subprocess.call('apt-get update', shell=True)
command = subprocess.call("apt-get install python-" + package, shell=True)
proc = subprocess.check_call(str(command), stdin=PIPE, stderr=subprocess.STDOUT)
stdoutdata, stderrdata = proc.communicate(),
assert proc.returncode == 0, 'Installed failed...'
print proc.returncode
except subprocess.CalledProcessError:
print >> sys.stderr, "Execution failed", 'OSError,', 'trying pip...'
'Installed virtualenv with pip...' if install_pip(package) else 'Pip failed...'
My question is how can I use subprocess.check_call
or subprocess.check_output
to check if the user already has virtualenv
installed or if it installed correctly. As of right now when I call .check_call()
it returns:
File "install_.py", line 121, in setup_virtal_env
proc = subprocess.check_call(str(command), stdin=PIPE, stderr=subprocess.STDOUT)
File "/usr/lib/python2.7/subprocess.py", line 535, in check_call
retcode = call(*popenargs, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Is there a way I can use subprocess
to check if virtualenv
is installed correctly?
When you want to use a command with arguments, you need to pass an array of args, like
suprocess.check_call(["apt-get","install", ...], ...)
Otherwise, the system will try to find an executable literally named "apt-get update", because spaces are legal filename characters. Of course it will then fail, giving you that error.
If you want to use a single string for your command, remember to use the shell=True
argument
suprocess.check_call("apt-get install", shell=True, ...)