Using “apt-get install xxx” inside Python script

前端 未结 5 737
既然无缘
既然无缘 2020-12-15 10:52

currently I need to install some package using apt or rpm, according the OS. I saw the lib \"apt\" to update or upgrade the system, but it is possible use it to install a si

相关标签:
5条回答
  • 2020-12-15 11:25

    For this particular task, as an alternative to subprocess you might consider using Fabric, a python deployment tool to automate builds.

    0 讨论(0)
  • 2020-12-15 11:31

    This is meant as an addition to Russell Dias's accepted answer. This adds a try and except block to output actionable error information rather than just stating there was an error.

    from subprocess import check_call, CalledProcessError
    import os
    try:
        check_call(['apt-get', 'install', '-y', 'filetoinstall'], stdout=open(os.devnull,'wb'))
    except CalledProcessError as e:
        print(e.output)
    
    0 讨论(0)
  • 2020-12-15 11:34

    Use this to redirect the output to /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.

    0 讨论(0)
  • 2020-12-15 11:38

    You can use check_call from the subprocess library.

    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.

    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 :) )

    0 讨论(0)
  • 2020-12-15 11:38

    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

    Thank you one more time from Argentina !

    0 讨论(0)
提交回复
热议问题