How to run python script from termux?

16.7k views Asked by At

I have managed to run the script from my computer with a cronjob. Was hard to accomplish but I've managed to see some sense. The problem is that most of the time I am not on my computer and wanted the script to run periodically. I know there are services like AWS or Google Cloud but was curious if it would be possible to run from my cellphone. That's why I ended up trying termux.

The problem is I can't figure out how to make it work and why it doesn't work.

My cronjobs on my mac are :

*/5 * * * * /PATH.TO/python3 /PATH.TO/main.py
30 * * * * /PATH.TO/python /PATH.TO/TEST.Json.py 

Even tho I take the same logic and apply it to my phone, it doesn't work

*/1 * * * * /data/data/com.termux/files/usr/bin/python /data/data/com.termux/files/home/storage/shared/scripts/script.py

Why's that?

2

There are 2 answers

1
Julia Fasick On

I suggest looking into Termux:Tasker here: https://wiki.termux.com/wiki/Termux:Tasker

You should be able to attach a cronjob process to Tasker and specify it to run in the background.

Unfortunately, it is 1.99$. You'll need Tasker and Termux:Tasker. Start by opening Termux. and type mkdir -p .termux/tasker. Move to the newly created folder with cd ./termux/tasker and use vim or nano to create your script. You'll probably have to do pkg install python too.

Then move to Tasker, create a task and name it whatever you want. Inside the task, add a Plugin:Termux command and set the config to the script you're running. I'd put at least 15 seconds before the timeout just in case. If you coose to run it in terminal you'll see the output, or you can add another command, this time Alert:Flash with the text %stdout. This will show the output of the previous command, in this case the python script.

Last step is to create a profile to trigger the task. I'm not sure what exactly you want it to trigger on, but for example you can have it go off every 2 minutes, every time you connect to a Wi-Fi network, or every time you receive a text. Then simply point it to the task you created earlier.

1
harsh ashesh On

So, I have been in the same situation you are stuck at. Did you perform the following actions?:

  1. Acquire wakelock on your phone
  2. crond start

If yes, then does your program run without cron, like if you do: /data/data/com.termux/files/usr/bin/python /data/data/com.termux/files/home/storage/shared/scripts/script.py