is there any way I can run python code in this way:
main code will run all the time ,
once every 5 min will run another function while running the main code.
my code is reading gps signal and send it to my server every 5 seconds.
I have to run another code that check the device cpu\file\temp every 5 min (this part take around 30 seconds )
can both of them run at the same time while still getting gps?
I have the GPS code ready and also the Check code ready - how do I combine them (if it's possiable)
Thanks ,
This might answer your question: Running Two Script at Once Using Bash
Based on the answer here, all you'd have to run is:
python script1.py &
python script2.py &
You can use the threading module, to do this task: it allows you to run functions as different processes seperate from the main program. Threading Documentation
I think you should get what you want with the following code:
import threading
def gpsJob():
threading.Timer(300.0, gpsJob).start()
# Here goes your GPS-code
gpsJob()
if __name__ == '__main__':
# main code
Related
Dear people of the internet, I need some help...
I have a Python script, main.py in which a user can enter 2 variables
First, ReminderTime is an int, second, ReminderText is a string. I want to send the two variables to another Python script, reminder.py.
The reminder script will do stuff with the two objects, and then it will use ToastNotifier to make a Windows notification, before shutting down.
The main script will still run in the foreground during that time. Is this possible?
You can use multiprocessing
Simple example:
p = Process(target=f, args=(ReminderTime, ReminderText))
p.start()
f - is function in your reminder.py that will start that script (like main in main.py by default)
args - is all arguments you need to send to this function
Also, you need to import you function import reminder.function_name
This code will start you f function in background, so main code will still runing.
So, according to this and this, to run two python scripts simultaneously I should run them from a batch file, separated by a &.
However, this does not seem to be working in a simple example.
I am currently trying this:
test1.py
import time
for i in range(5):
time.sleep(1)
print("Printing, test1:"+str(i))
test2.py
import time
for i in range(5):
time.sleep(2)
print("Printing, test2:"+str(i))
batch file
call "C:\Users\Username\Anaconda3\Scripts\activate.bat"
"C:\Users\Username\Anaconda3\python.exe" "C:\Users\Python\Documents\Python\Test\test1.py" &
"C:\Users\Username\Anaconda3\python.exe" "C:\Users\Python\Documents\Python\Test\test2.py" &
I would expect to see the results mingled, however, this is the outcome:
It is clear that script 2 is running after script 1.
Any ideas?
Thanks!
Thanks to #jasonharper pointing out that the two solutions I had found were specific to Unix, not Windows (although I had searched for Windows), I was able to find this other post, that is for Windows.
With a little adaptation to conda, I was able to get bot scritps to run simultaniously, like this:
batch file
call "C:\Users\Username\Anaconda3\Scripts\activate.bat"
start python "C:\Users\Username\Documents\Python\Test\test1.py" &
start python "C:\Users\Username\Documents\Python\Test\test2.py" &
The results are pretty cool.. Two python windows running simultaneously:
Thanks everyone!
Use multiprocessing or threading modules of python
import time
import threading
def test1():
for i in range(5):
time.sleep(1)
print("Printing, test1:"+str(i))
def test2():
for i in range(5):
time.sleep(2)
print("Printing, test2:"+str(i))
x = threading.Thread(target=test1)
t = threading.Thread(target=test2)
x.start()
t.start()
I'm trying to run multiple exe's (12 of them), because of computer resources I can spawn maximum 4 at a time before I get performance degradation.
I'm trying to find if there is a way to call 4 exe's at a time and as soon as one of them finishes, to call another exe to fill the resources that have freed up
My current code does this:
excs = [r"path\to\exe\exe.exe",r"path\to\exe\exe.exe",r"path\to\exe\exe.exe",r"path\to\exe\exe.exe"]
running = [subprocess.Popen(ex) for ex in excs]
[process.wait() for process in running]
It repeats this process three times so that it runs all 12. Unfortunately it means that it needs to wait for all of them to finish before moving on to the next set. Is there a more efficient way of doing this?
For the record, all of the exe's have different run times.
Python has ThreadPoolExecutor which makes this very convenient
import subprocess
from concurrent.futures import ThreadPoolExecutor
def create_pool(N,commands):
pool = ThreadPoolExecutor(max_workers=N)
for command in commands:
pool.submit(subprocess.call, command)
pool.shutdown(wait=False)
def main():
N_WORKERS=4
commands = [job1, job2, ...]
create_pool(N_WORKERS, commands)
I got temperature, pressure, and altitude readings on my PI using a sensor:
The problem is, to see the results, I have to execute the code.py every time by myself. I am trying to automate it somehow so it will keep running itself for the time I want.
Once that is automated, would like to save the results and analyze the output after some time.
Is there a way I can write code for both the tasks?
Thank you.
There are two things required here. First a script i.e code.py to log the functional behavior like temperature, pressure, and altitude readings along with error/response during the process. Another is the script executions logs i.e a success or failure during the scheduled time and other system logs.
For first job, you have to do by your self but ensure to have a logger module in place to log the process flow.
For Second job, you can use OS provided scheduler crontab for Linux based os. For example to execute script every minutes
* * * * * python /home/script/code.py > /home/script/code.log 2>&1
For more about scheduler jobs, you can refer here
The time module is your friend here. You can set up an infinite loop with while True: and use time.sleep(secs) at the end of the loop (after output).
I'd use additional controller script like this:
import subprocess;
import time;
import sys;
x = True;
while x:
while exit_code!=0:
try:
exit_code = subprocess.check_call(['python', 'collect_data.py', '-cli_args_if_needed']);
except:
print(sys.exec_info()[1]);
print('Relaunching in 5 seconds');
time.sleep(5)
Looked at all the similar questions but unable to get the syntax correct. I have a python script that runs a single command at the moment. What I need to do is have this command repeat itself over and over...indefinitely...at certain intervals. Here is my script:
#! /usr/bin/env python
import sys
from scapy.all import sr1,IP,ICMP,UDP,send,DNS,DNSQR
p=send(IP(dst="192.168.1.128")/UDP()/DNS(rd=1,qd=DNSQR(qname="domain.com")), count=100 )
if p:
p.show()
This runs fine from the command line. However I need it to repeat every 30 seconds or 1 minute. How would I tell it to do that inside the script? I know I can probably set this up as a cron job but I'd like to know how to script it. Thanks!
You can use the time module's sleep() method inside a while True loop.
#! /usr/bin/env python
import sys
import time
from scapy.all import sr1,IP,ICMP,UDP,send,DNS,DNSQR
while True:
p=send(IP(dst="192.168.1.128")/UDP()/DNS(rd=1,qd=DNSQR(qname="domain.com")), count=100)
if p:
p.show()
time.sleep(60) # sleep for one minute
you can put a infinite while loop and add sleep of 30 seconds in every iteration. The other option could be set the script into cron job.
The advisable option is cronjob as in case python script exit due to any exception or error, cron can re-run it in next cycle.
Create a while loop. True is always True, so the loop keeps running. After the commands wait a while.
#! /usr/bin/env python
import sys, time
interval = 60 #1 minute
from scapy.all import sr1,IP,ICMP,UDP,send,DNS,DNSQR
while True:
p=send(IP(dst="192.168.1.128")/UDP()/DNS(rd=1,qd=DNSQR(qname="domain.com")), count=100 )
if p:
p.show()
time.sleep(interval)
The infinite loop with the sleep as mentioned in the above answers is the simplest way to do what you want. However, if you do that, your program becomes a daemon which you have to monitor and make sure is running. This has some costs that you should be aware of up front.
I would prefer to use cron to run it every n minutes or something similar. Yet another way, which is similar to the inifinite loop is to the use the python sched module to run a mini cron like system inside your program.