3

I want a simple script to stay running in the background. It currently looks like this:

import keyboard

while True:
    keyboard.wait('q')
    keyboard.send('ctrl+6')

Now, this works already (When q is pressed, it also presses ctrl+6), but I guess there has to be a more efficient way of keeping a program running, so it can act on input.

I would rather not use an infinite while loop.

I'm on Windows

Thanks :)

2
  • 7
    That's, actually how it's done tho. It's the most efficient way there is. You could insert a time.sleep(0.025) or something similar to not hog your CPU tho (unless keyboard.wait() is a blocking call, then it doesn't matter. And perhaps implement a event-driven trigger so the actions isn't depending on the time between sleeps/loops (for instance, import select does this). But a while loop is one of the most efficient ways to keep something alive while waiting for a condition. Commented Jan 21, 2019 at 18:37
  • Thanks a lot :) I'll also look into the select module Commented Jan 21, 2019 at 18:52

3 Answers 3

5

You can using nohup

nohup python script.py > log.txt 2>&1 &

If you want check command is running

ps aux | grep script
user    5124 <- process_id  1.0  0.3 214588 13852 pts/4    Sl+  11:19   0:00 python script.py

Kill command is running

kill -9 [process_id]
Sign up to request clarification or add additional context in comments.

Comments

3

I was searching for something same and landed here. Here is another solution. Its working fine for me. Maybe useful to someone else too.

Use the -i option at the command line. Thus, if your Python script is foo.py, execute the following at the command line:

python -i foo.py

Comments

3

It depends on the platform you are using. In Linux from the terminal you can run your script with & at the end to start it as a background process:

python script.py &

You can then find your background process with:

ps -ef | grep script.py

And kill the process:

kill <pid number>

In windows, it's a bit more complex but the answer is here.

Note: I would add a time.sleep(0.025) command to your script (like mention in the comments).

2 Comments

I'm on Windows. Sorry for not stating that, I edited my question. Thanks for your help :)
There's a section in my question answering for windows!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.