Daniel Correia
Daniel Correia

Reputation: 73

Executing a Python script without spawning a new process with subprocess

I'm making a python script (start.py) to run multiple (4) python scripts. My code:

    import subprocess
from time import sleep

y=(0.2)
sleep (y)
subprocess.Popen(["python", 'a1.py'])
sleep (y)
subprocess.Popen(["python", 'a2.py'])
sleep (y)
subprocess.Popen(["python", 'a3.py'])
sleep (y)
subprocess.Popen(["python", 'a4.py'])

When I run start.py the four scripts run in background as I expected, but each one with a process ID. Is it possible to have one PID for all?

And how can I make the start.py run at startup as a service? (i'm using raspberry pi).

Upvotes: 2

Views: 1412

Answers (2)

Najeeb Choudhary
Najeeb Choudhary

Reputation: 396

you can try this code:

import subprocess
from time import sleep
import sys
y=(0.2)
sleep(y)
subprocess.Popen([sys.executable, 'a1.py'],stdin=subprocess.PIPE)
sleep(y)
subprocess.Popen([sys.executable, 'a2.py'],stdin=subprocess.PIPE)
sleep(y)
subprocess.Popen([sys.executable, 'a3.py'],stdin=subprocess.PIPE)
sleep(y)
subprocess.Popen([sys.executable, 'a4.py'],stdin=subprocess.PIPE)

i recommaned to execute script one by one if all think is good then you can execute above program

Upvotes: -2

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83788

To run the Python script inline within the same interpreter you can use execfile:

https://docs.python.org/2/library/functions.html#execfile

Python 3 equivalent:

What is an alternative to execfile in Python 3?

To start a script as a background service it is best to use external tool like Linux's systemd or supervisord for this purpose.

Upvotes: 3

Related Questions