mao95
mao95

Reputation: 1122

How to delay the execution of a script in Python?

I'm working with a Python script and I have some problems on delaying the execution of a Bash script.

My script.py lets the user choose a script.sh, and after the possibility to modify that, the user can run it with various options.

One of this option is the possibility to delay of N seconds the execution of the script, I used time.sleep(N) but the script.py totally stops for N seconds, I just want to retard the script.sh of N seconds, letting the user continue using the script.py.

I searched for answers without success, any ideas?

Upvotes: 1

Views: 3139

Answers (3)

MaxNoe
MaxNoe

Reputation: 14987

You can start the script in a New thread, sleeping before running it.

Minimal example:

import subprocess as sp
from threading import Thread
import time

def start_delayed(args, delay):
    time.sleep(delay)
    sp.run(args)

t = Thread(target=start_delayed, kwargs={'args': ['ls'], 'delay': 5})
t.start()

Upvotes: 3

Charles Duffy
Charles Duffy

Reputation: 295291

Consider using a Timer object from the threading module:

import subprocess, threading
t = threading.Timer(10.0, subprocess.call, args=(['script.sh'],))
t.start()

...the above running script.sh after a 10-second delay.


Alternately, if you want to efficiently be able to run an arbitrary number of scheduled tasks with only a single thread controlling them, consider using a scheduler from the tandard-library sched module:

import sched, subprocess

s = sched.scheduler(time.time, time.sleep)
s.enter(10, subprocess.call, (['script.sh'],))
s.run()

This will run script.sh after 10 seconds have passed -- though if you want it to run in the background, you'll want to put it in a thread (or such) yourself.

Upvotes: 1

polarise
polarise

Reputation: 2413

You should run sleep using subprocess.Popen before calling script.sh.

Upvotes: 0

Related Questions