0

I have a python script that updates a .txt file.

When I run the file manually in the terminal it works, it also updates the file. However, this seems to only be a problem when it is run with cron.

The response in the log file is:

No such file or directory: 'uploads/test.txt'

The cron command for this is:

* * * * * /usr/bin/python3 /root/script.py >> /root/log.log  2>&1

I'm literally stumped. Any solutions?

JamesG
  • 1,552
  • 8
  • 39
  • 86
  • Have you tried using an absolute path to the `test.txt` file in `script.py`? – user2390182 Nov 01 '17 at 14:11
  • I tried using `~/root/uploads.test.txt` is that the absolute path? – JamesG Nov 01 '17 at 14:12
  • That doesn't look right. Try `/root/uploads/test.txt`! Without the `~` which is the path to the curretn user's home folder. – user2390182 Nov 01 '17 at 14:13
  • @CharlesDuffy clearly I meant `/` not `.` and the uploads/test.txt is references in the script that is run. – JamesG Nov 01 '17 at 14:30
  • By default, cron jobs run in `/`, so `uploads/test.txt` will be looking for `/uploads/test.txt`, which you probably don't have. – Charles Duffy Nov 01 '17 at 14:37
  • That file exists in the same spot as the script.py – JamesG Nov 01 '17 at 14:51
  • Yes, but `.` isn't the location of the script, it's the current working directory of the process that started the script. Entirely different things. – Charles Duffy Nov 01 '17 at 15:00
  • ...that said, making it clear that that's the source of the misunderstanding here has allowed a dupe to be identified. – Charles Duffy Nov 01 '17 at 15:03
  • @JamesG, ...btw, `~` is syntax for a shell expansion. It doesn't have meaning to the OS-level `open()` syscall or other language wrappers for it; there's an `os.path` library call you need to use if you want `~` to be replaced with the current user's home directory in Python. – Charles Duffy Nov 01 '17 at 18:31

1 Answers1

1

uploads/test.txt is a relative path. Cron is not running from the parent directory of uploads. Use an absolute path to uploads (eg. /data/foo/uploads/test.txt, or cwd to parent directory of uploads.

r_2
  • 1,640
  • 1
  • 11
  • 11
  • 1
    You might also suggest `cd /data/foo && exec python ...` as an alternative (the `exec` is just a performance optimization -- means that the shell doesn't need to stick around in memory after `python` is started -- but the `&&` is critical: Means we don't try to run the Python interpreter if we can't `cd` to the directory that the script expects to be started from). – Charles Duffy Nov 01 '17 at 14:36