使用子进程检查 sudo-apt install Return 值?

Using Subprocess to Check sudo-apt install Return Value?

我目前正在使用 Python 2.7 编写 shell 脚本。要安装虚拟环境,我使用以下内容:

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...'

我的问题是如何使用 subprocess.check_callsubprocess.check_output 检查用户是否已经安装了 virtualenv 或者安装是否正确。截至目前,当我调用 .check_call() 时 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

有什么方法可以使用 subprocess 检查 virtualenv 是否安装正确?

当你想使用带参数的命令时,你需要传递一个args数组,比如

suprocess.check_call(["apt-get","install", ...], ...)

否则,系统将尝试查找字面上名为 "apt-get update" 的可执行文件,因为空格是合法的文件名字符。当然它会失败,给你那个错误。

如果你想为你的命令使用单个字符串,记得使用 shell=True 参数

suprocess.check_call("apt-get install", shell=True, ...)