Jojo
Jojo

Reputation: 131

Simple way to keep a Python script running?

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 :)

Upvotes: 3

Views: 29903

Answers (3)

Hans Daigle
Hans Daigle

Reputation: 364

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).

Upvotes: 3

Adnan Ali
Adnan Ali

Reputation: 3055

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

Upvotes: 3

Giang
Giang

Reputation: 2729

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]

Upvotes: 5

Related Questions