With the era of multi-core CPU, parallel, concurrency or multiprocessing is quite possible now. Below is an example of a Python code that shows how to use multiprocessing module to run multiple commands.
When using Python's multiprocessing module, it's often useful to confirm that multiple CPU cores are being utilized. This can be done using the top command in your terminal. Once top is running, pressing the 1 key will toggle the display to show the utilization of each individual CPU core.
Sample image output of "top" showing all the available cores on the device.
Jeremiah 29:11:
"For I know the plans I have for you,” declares the Lord, “plans to prosper you and not to harm you, plans to give you hope and a future.
Let God unfold His plan in your life. Let Him lead the way.
import multiprocessing
import subprocess
# Shell command/s Function
def multi_run_command(command):
try:
result = subprocess.run(command, shell=True, capture_output=True, text=True)
return f"Command: {command}\nOutput:\n{result.stdout}"
except Exception as e:
return f"Command: {command}\nError: {e}"
if __name__ == "__main__":
# List of dig commands to run / Replace the commands as desired
commands = ["dig @1.1.1.1 google.com", "dig @8.8.4.4 yahoo.com", "dig @9.9.9.9 bing.com"]
# Create and specify limit of pool worker processes
with multiprocessing.Pool(processes=3) as pool: #limit to 3 cores or workers
results = pool.map(multi_run_command, commands) #use the map builtin to get the command list
# Print the list results using for loop
for result in results:
print(result)
Sample output of the above code:
When using Python's multiprocessing module, it's often useful to confirm that multiple CPU cores are being utilized. This can be done using the top command in your terminal. Once top is running, pressing the 1 key will toggle the display to show the utilization of each individual CPU core.
Sample image output of "top" showing all the available cores on the device.
Jeremiah 29:11:
"For I know the plans I have for you,” declares the Lord, “plans to prosper you and not to harm you, plans to give you hope and a future.
Let God unfold His plan in your life. Let Him lead the way.
Comments
Post a Comment