简体   繁体   English

在不使用子进程生成新进程的情况下执行 Python 脚本

[英]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.我正在制作一个 python 脚本 (start.py) 来运行多个 (4) python 脚本。 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.当我运行 start.py 时,四个脚本按照我的预期在后台运行,但每个脚本都有一个进程 ID。 Is it possible to have one PID for all?是否可以为所有人拥有一个 PID?

And how can I make the start.py run at startup as a service?以及如何使start.py在启动时作为服务运行? (i'm using raspberry pi). (我正在使用树莓派)。

To run the Python script inline within the same interpreter you can use execfile :要在同一个解释器中内联运行 Python 脚本,您可以使用execfile

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

Python 3 equivalent: Python 3 等效项:

What is an alternative to execfile in Python 3? Python 3 中 execfile 的替代方法是什么?

To start a script as a background service it is best to use external tool like Linux's systemd or supervisord for this purpose.要将脚本作为后台服务启动,最好为此目的使用外部工具,如 Linux 的systemdsupervisord

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我建议一个一个执行脚本,如果一切都认为是好的,那么你可以执行上面的程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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