简体   繁体   English

在Python脚本中使用“apt-get install xxx”

[英]Using “apt-get install xxx” inside Python script

currently I need to install some package using apt or rpm, according the OS. 根据操作系统,目前我需要使用apt或rpm安装一些软件包。 I saw the lib "apt" to update or upgrade the system, but it is possible use it to install a single package? 我看到lib“apt”更新或升级系统,但有可能用它来安装一个软件包吗?

I was trying to use too "subprocess": 我试图使用“subprocess”:

subprocess.Popen('apt-get install -y filetoinstall', shell=True, stdin=None, stdout=None, stderr=None, executable="/bin/bash")

But this command shows all process in the shell, I cannot hide it. 但是这个命令显示了shell中的所有进程,我无法隐藏它。

Thank you for your help. 谢谢您的帮助。

You can use check_call from the subprocess library. 您可以使用subprocess库中的check_call

from subprocess import STDOUT, check_call
import os
check_call(['apt-get', 'install', '-y', 'filetoinstall'],
     stdout=open(os.devnull,'wb'), stderr=STDOUT) 

Dump the stdout to /dev/null , or os.devnull in this case. 在这种情况下,将stdout转储到/dev/nullos.devnull

os.devnull is platform independent, and will return /dev/null on POSIX and nul on Windows (which is not relevant since you're using apt-get but, still good to know :) ) os.devnull是独立os.devnull平台的,它将在POSIX上返回/dev/null并在Windows上返回nul (这是不相关的,因为你使用apt-get但仍然很好知道:))

Thank guys ! 谢谢你们! I use part of each solution. 我使用每个解决方案的一部分。 My code: 我的代码:

proc = subprocess.Popen('apt-get install -y FILE', shell=True, stdin=None, stdout=open(os.devnull,"wb"), stderr=STDOUT, executable="/bin/bash")
proc.wait()

Added: stdout and .wait 补充:stdout和.wait

Thank you one more time from Argentina ! 再次感谢阿根廷人!

对于这个特定的任务,作为subprocess的替代方案,您可以考虑使用Fabric ,这是一个自动化构建的python部署工具。

Use this to redirect the output to /dev/null: 使用此选项将输出重定向到/ dev / null:

proc = subprocess.Popen('apt-get install -y filetoinstall', shell=True, stdin=None, stdout=open("/dev/null", "w"), stderr=None, executable="/bin/bash")
proc.wait()

The call to .wait() will block until the apt-get is complete. 对.wait()的调用将阻塞,直到apt-get完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM