使用apt modu更新python本身

2024-04-24 22:50:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个python脚本,它将作为user-data-script在EC2机器上运行。我在想办法升级机器上的软件包,类似于bash命令:

$ sudo apt-get -qqy update && sudo apt-get -qqy upgrade

我知道我可以使用python中的apt包来完成此操作:

^{pr2}$

问题是,如果python本身是升级的包之一,会发生什么。有没有办法在升级后重新加载解释器和脚本,并在它停止的地方继续?在

现在,我唯一的选择是使用shell脚本作为用户数据脚本,唯一的目的是升级包(可能包括python),然后将其余代码放入python。我想省去使用shell脚本的额外步骤。在


Tags: 命令脚本bash机器datagetsudoscript
2条回答

使用链接。在

#!/bin/sh
cat >next.sh <<'THEEND'
#!/bin/sh
#this normally does nothing
THEEND
chmod +x next.sh

python dosomestuff.py

exec next.sh

在Python应用程序中,您可以编写一个shell脚本来执行您需要的操作。在本例中,shell脚本将升级Python。因为它是在Python关闭之后运行的,所以没有冲突。实际上,next.sh可以启动同一个(或另一个)Python应用程序。如果您在两个shell脚本first.shnext.sh之间交替使用,则可以根据需要将这些调用链接在一起。在

我想我明白了:

def main():
    import argparse
    parser = argparse.ArgumentParser(description='user-data-script.py: initial python instance startup script')
    parser.add_argument(' skip-update', default=False, action='store_true', help='skip apt package updates')
    # parser.add_argument whatever else you need
    args = parser.parse_args()

    if not args.skip_update:
        # do update
        import apt
        cache = apt.Cache()
        cache.update()
        cache.open(None)
        cache.upgrade()
        cache.commit()

        # restart, and skip update
        import os, sys
        command = sys.argv[0]
        args = sys.argv
        if skipupdate:
            args += [' skip-update']
        os.execv(command, args)

    else:
        # run your usual code
        pass

if __name__ == '__main__':
    main()

相关问题 更多 >