Search code examples
python-3.xshebang

shebang #!/usr/bin/env python3 not working on my macos


#!/usr/bin/env python3.9 doesn't work in crontab, while #!/Library/Frameworks/Python.framework/Versions/3.9/bin/python3 does.

Strange thing is, both are working fine if the script is run from the terminal command line.

Yet, if run from crontab, only the latter works.

Here is the error log when #!/usr/bin/env python3.9 was used in cron:

    from typing import List
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/typing.py", line 23, in <module>
    import contextlib
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py", line 6, in <module>
    from functools import wraps
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/functools.py", line 22, in <module>
    from types import GenericAlias
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/types.py", line 296, in <module>
    GenericAlias = type(list[int])
TypeError: 'type' object is not subscriptable

Looks to me these two shebang lines are pointing to the same thing?

(base) ganningxu@Gannings-iMac:~$ python3.9
Python 3.9.1 (v3.9.1:1e5d33e9b9, Dec  7 2020, 12:10:52) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> ^D
(base) ganningxu@Gannings-iMac:~$ (base) ganningxu@Gannings-iMac:~$ /Library/Frameworks/Python.framework/Versions/3.9/bin/python3
Python 3.9.1 (v3.9.1:1e5d33e9b9, Dec  7 2020, 12:10:52) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Solution

  • Most likely you're getting that discrepancy because your crontab's PATH is different than your terminal PATH. Have you checked that /Library/Frameworks/Python.framework/Versions/3.9/bin/ is part of crontab's PATH? If not, you can set it directly on crontab like this.

    When crontab runs your #!/usr/bin/env python3.9, env will look for python3.9 in the directories specified in the PATH environment variable that crontab has, but that is initialized differently depending on which program is running (cron, interactive terminal, etc).