简体   繁体   English

crontab:运行 Python 脚本时找不到命令

[英]crontab: Command not found when running Python script

I wrote a Python script which backs up mongoDB, and it works fine when I test run directly in terminal.我写了一个 Python 脚本来备份 mongoDB,当我直接在终端中测试运行时它工作正常。

However, I get an error from cron saying mongodump: command not found - although the command mongodump works fine when I run the script directly in terminal.但是,我从 cron 收到一个错误,说mongodump: command not found - 尽管当我直接在终端中运行脚本时,命令mongodump工作正常。

Contents of crontab -e : crontab -e的内容:

* * * * * cd <path-to-script> && python3 script.py

After looking into the post provided by S3DEV's.在查看了 S3DEV 提供的帖子后。

Running the full env path of mongodump into the python script worked.将 mongodump 的完整环境路径运行到 python 脚本中有效。 To get the full path of mongodump, in terminal:要获取 mongodump 的完整路径,请在终端中:

which mongodump
>>/usr/local/bin/mongodump

In my case i am using os.system() in my script.就我而言,我在脚本中使用 os.system() 。

os.system(/usr/local/bin/mongodump [commands])

instead of代替

os.system(mongodump [commands])

This is because programs started from cron don't get the environment your login shell uses.这是因为从 cron 启动的程序没有得到您登录 shell 使用的环境。 In particular, PATH is usually quite minimal.特别是, PATH通常非常小。 The tried and tested way to run scripts from cron is:从 cron 运行脚本的久经考验的方法是:

  • Always use an absolute path to a script in the crontab, say /path/to/script .始终使用 crontab 中脚本的绝对路径,例如/path/to/script
  • The beginning of /path/to/script sets and exports PATH and any other variables needed, eg with export PATH=$(/usr/bin/getconf PATH):/usr/local/bin /path/to/script的开头设置和导出PATH以及所需的任何其他变量,例如export PATH=$(/usr/bin/getconf PATH):/usr/local/bin

You can test whether any script would run with a reduced environment with您可以测试是否有任何脚本可以在简化的环境中运行

env -i HOME=$HOME /path/to/script

If that runs ok, it is ready for cron.如果运行正常,它就可以用于 cron 了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM