Restart python-script from within itself

前端 未结 9 1865
谎友^
谎友^ 2020-12-02 15:27

I have a python-based GTK application that loads several modules. It is run from the (linux) terminal like so:

./myscript.py --some-flag setting

相关标签:
9条回答
  • 2020-12-02 16:08

    You're looking for os.exec*() family of commands.

    To restart your current program with exact the same command line arguments as it was originally run, you could use the following:

    os.execv(sys.argv[0], sys.argv)
    
    0 讨论(0)
  • 2020-12-02 16:09

    Inspired by @YumYumYum and fixed the problem Using restart.sh and os.execl

    restart.sh
    
    #!/bin/bash/
    pkill -f main.py
    python main.py
    

    Add this to your main.py

    os.excel("restart.sh","")
    
    0 讨论(0)
  • 2020-12-02 16:19

    I think this is a more elaborate answer, as sometimes you may end up with too many open file objects and descriptors, that can cause memory issues or concurrent connections to a network device.

    import os
    import sys
    import psutil
    import logging
    
    def restart_program():
        """Restarts the current program, with file objects and descriptors
           cleanup
        """
    
        try:
            p = psutil.Process(os.getpid())
            for handler in p.get_open_files() + p.connections():
                os.close(handler.fd)
        except Exception, e:
            logging.error(e)
    
        python = sys.executable
        os.execl(python, python, *sys.argv)
    
    0 讨论(0)
提交回复
热议问题