当前位置: 代码迷 >> python >> 使用子进程检查sudo-apt安装的返回值?
  详细解决方案

使用子进程检查sudo-apt安装的返回值?

热度:79   发布时间:2023-06-16 10:21:13.0

我目前正在使用Python 2.7编写Shell脚本。 要安装virtual-env,我使用以下工具:

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_call或subprocess.check_output检查用户是否已经安装了virtualenv或安装正确。 截至目前,当我调用.check_call()时,它会返回

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

有没有一种方法可以使用子进程来检查virtualenv是否已正确安装/安装? 非常感谢高级!

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

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

否则,由于空格是合法的文件名字符,因此系统将尝试找到一个字面名为“ apt-get update”的可执行文件。 当然它将失败,并给您该错误。

如果要为命令使用单个字符串,请记住使用shell=True参数

suprocess.check_call("apt-get install", shell=True, ...)
  相关解决方案