I have multiple codes written in Python, and I want to let one program control the start of them. There are times like that. This time, I will introduce how to execute another program you want to start asynchronously from the program.
Windows10 python 3.7.6 anaconda 20.02
import subprocess
command = [python (File).py (argument)]
proc = subprocess.Popen(command) #->Command is executed(Do not wait for the end of processing)
result = proc.communicate() #->Wait for the end
It's a code without any twist, but I created two files as a trial to see if it works for the time being. call.py is designed to output the given arguments. List the commands by enclosing them in "" separated by spaces.
call.py
import sys
from time import sleep
sleep(1) #Have them sleep for a second(To check if it is asynchronous)
args = sys.argv[1]
print(args)
main.py
import subprocess
command = ["python","call.py,"I was called!"]
proc = subprocess.Popen(command)
print("Calling")
proc.communicate()
Execution result
Since the "calling" of main is printed first, You can see that ** not waiting for the process executed by subprocess.Popen () **.
When I call it with subprocess.Popen (), I am concerned about ** processing time **. Try calling call_2.py, which performs the following processing for a 1280 x 800 image.
call_2.py
from time import time
import numpy as np
import cv2
start = time()
img = cv2.imread("sample.png ")
resize = cv2.resize(img,dsize=None,fx=0.5,fy=0.5) #resize
kernel = np.ones((5,5),np.uint8)
erosion = cv2.erode(resize,kernel) #erode
cv2.imwrite("resize.png ",erosion)
end = time() - start
print(end)
Now when you run it with python main.py and when you run it with python call_2.py I compared the time of the end to be printed. I tried going in and out of the console several times, ** The processing time was about the same whether it was cached or not **. (The actual numbers are omitted because they may depend on the execution environment.)
I showed you how to run another py file with subprocess.Popen (). There was no difference in processing speed in the Windows environment. I'm happy that there is no speed bottleneck. However, it may change if the environment is Linux.
We hope you find this helpful.
** Please also refer to the following site ** Official documentation (Python 3.8.5) If the file you want to execute exists in another directory Execute shell command from Python! Summary of how to execute a subprocess with subprocess Execute Linux command from Python with subprocess
** A book that seems to be helpful (I just want to read it ...) ** Expert Python Programming Revised 2nd Edition
Recommended Posts