Search code examples
pythonpython-3.xpm2

How to run Python module with PM2 ecosystem file?


I can run a Python script with PM2 with the following ecosystem file:

{
    "apps": [{
        "name": "my_app",
        "script": "script.py",
        "instances": "1",
        "wait_ready": true,
        "autorestart": false,
        "interpreter" : "/home/my_user/.cache/pypoetry/virtualenvs/my_app-ij6Dv2sY-py3.10/bin/python",
    }]
}

That works fine but i have another program that i can only start this way:

python -m my_app

But for this i can not simply change the ecosystem file to this:

{
    "apps": [{
        "name": "my_app",
        "script": "-m my_app",
        "instances": "1",
        "wait_ready": true,
        "autorestart": false,
        "interpreter" : "/home/my_user/.cache/pypoetry/virtualenvs/my_app-ij6Dv2sY-py3.10/bin/python",
    }]
}

PM2 will run it without errors but my app will not be running. How can i use -m my_app with a PM2 ecosystem file?


Solution

  • You can simply use the args field in your file to pass the module name. like that:

    {
        "apps": [{
            "name": "my_app",
            "script": "run_module.py",
            "args": "my_app",
            "instances": "1",
            "wait_ready": true,
            "autorestart": false,
            "interpreter" : "/home/my_user/.cache/pypoetry/virtualenvs/my_app-ij6Dv2sY-py3.10/bin/python",
        }]
    }
    

    then you create a python file run_module.py in the same folder and it will work:

    import runpy
    import sys
    
    if __name__ == "__main__":
        module_name = sys.argv[1]
        runpy.run_module(module_name, run_name="__main__")