Score:0

How to run a python script in a specific directory automatically?

tw flag

I have a python script that I wish to run at 5pm every Friday.
How can I achieve that ?

I understand I could do this through cron. However, as I have used relative file paths in the Python script and therefore must be run in the specific directory with the other files. I have seen I may be able to achieve this using the pipe operator however I have been unable to find an example.

Score:0
in flag

You can just cd into the directory before running the script.

0 17 * * Fri cd /path/to/dir && python myscript.py

No wrapper necessary.

Prem avatar
cn flag
There are various other ways too. I did not want to include this , because I have sometimes come across Cases where the cron line was too cumbersome , when the Parameters were complex , with single quotes , double quotes & escape sequences. I usually took all that complexity , put it into a Wrapper Script & kept the cron line simple !
Score:0
cn flag

There are various ways to achieve this , I will list just 2 ways :

(1) Use a Bash "Wrapper Shell Script" in your Cron Job to Execute @ 5PM.
In the "Wrapper Script" , first "cd X" where X is the necessary Directory.
Then Execute the Python Script. It will run in the Directory X.

# My Bash Wrapper Script  
cd X # use the necessary Directory here  
python MyPythonScript.py  

(2) In your Python Script , import module "os" & use "os.chdir" to Change Directory & then continue with the Python Script.

# My Python Script  
import os  
os.chdir(X) # use necessary Directory here  
# continue with Python Script  
# no other Changes necessary  

These 2 ways are very easy to use.

in flag
these shebang lines are invalid
Prem avatar
cn flag
I wanted to use Comments , though typing habit made those accidental shebangs. I have made the Corrections , @GeraldSchneider , thank you.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.