简体   繁体   中英

Run python script multiple times as a background process with different configuration

I used php to run python script on Linux via web after running and I get process ID

<!DOCTYPE html>
<html>
   <body>
      <?php
      echo 'Starting the mapping process';
      echo exec('nohup python cloudemir.py '.$_GET[message].' > /dev/null 2>&1 & echo $! &');
     ?>
  </body>
</html> 

which is then used to kill the process when I don't need it which works fine

<!DOCTYPE html>
<html>
    <body>
        <?php
        $pid=$_GET['pid'];
        echo exec("kill -9 $pid");
        ?>
    </body>
</html>

The python script I used is just publishing one message via MQTT every second. The problem is that I can't change the message content.

If the message is Hi, and I run this process, it says "Hi", "Hi"... every second. If I change python script message to Hi2, and run it again I get new process id and new message is Hi2 every second and there is no Hi message any more.

I need it to run separately and to get both messages, and when needed to kill one of them. I need it to be able to run unlimited number of instances of that python sctipt with different configuiration, I don't need to build new scripts.

domain/run.php?message=Hi

domain/run.php?message=Hi2

This should print Hi, Hi2, Hi, Hi2

domain/run.php?message=Hi

domain/run.php?message=Hi2

domain/run.php?message=Hi3

This should print Hi, Hi2, Hi3, Hi, Hi2, Hi3

In both cases it prints only last message

I even tried the same without php, but calling the script from another python script with

proc = subprocess.Popen("nohup python cloudemir.py "+content+" > /dev/null 2>&1 &", shell=True)

But it remains the same, last call overwrites the previous

You should use sys.argv . As an example of the file cloudemir.py :

import sys

print(sys.argv[0])

And then you can call it with:

python cloudemir.py Hi # First time
python cloudemir.py Hi2 # Second time

This way the name after cloudemir.py will be inputed as a param to the python program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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