Python script elicits error when run in cron job but at no other time

cron, python, shell

Solution

You are probably running your script from cron with a different version of Python that doesn't support the dictionary comprehension syntax.

To fix this, either explicitly add your desired Python version in the shebang line:

#!/usr/bin/env python2.7

or launch your script from cron through the correct command:

* * * * /usr/bin/python2.7 /path/to/script.py

Problem

I have a shell script that includes execution of a python script. When I run it manually in terminal, it works fine. However when I execute the shell script in a cron job, the python script fails. The error is apparently triggered while functions are being imported from module1 into module2. The function referenced by the error is not among the functions being imported, nor does the function where the syntax error is supposed to be elicit an error when it is executed by itself. Here's the error that gets logged when I run the cron job: ``` File "/Users/me/module2.py", line 5, in <module> from module1 import consolidate_rankings, build_all File "/Users/me/module1.py", line 159 things = {row["thing"]: row for row in rows} ^ SyntaxError: invalid syntax ``` The module2 script is pretty straightforward: ``` #!/usr/bin/env python from module1 import consolidate_rankings, build_all consolidate_rankings() build_all() ``` Here's the line that calls this in the shell script: python /Users/me/module2.py Anyone have any idea what's going on here?

Original source

Related problems