Not able to start python program via sh / crontab
Question: I try to start a python program called ocrmypdf from a script or as a cronjob.

It works perfectly from the terminal,

    
    
    pi@piscan:~ $ ocrmypdf 
    usage: ocrmypdf [-h] [--verbose [VERBOSE]] [--version] [-L FILE] [-j N] [-n]
                [--flowchart FILE] [-l LANGUAGE] [--title TITLE]
                [--author AUTHOR] [--subject SUBJECT] [--keywords KEYWORDS]
                [-d] [-c] [-i] [--oversample DPI] [-f] [-s]
                [--skip-big MPixels] [--tesseract-config TESSERACT_CONFIG]
                [--pdf-renderer {auto,tesseract,hocr}]
                [--tesseract-timeout TESSERACT_TIMEOUT] [-k] [-g]
                input_file output_file
    ocrmypdf: error: the following arguments are required: input_file, output_file
    

but from another shell it breaks for reasons I do not understand.

    
    
    pi@piscan:~ $ sh ocrmypdf
    sh: 0: Can't open ocrmypdf
    pi@piscan:~ $ which ocrmypdf 
    /usr/local/bin/ocrmypdf
    pi@piscan:~ $ sh $(which ocrmypdf)
    import: unable to open X server `' @ error/import.c/ImportImageCommand/364.
    import: unable to open X server `' @ error/import.c/ImportImageCommand/364.
    from: can't read /var/mail/ocrmypdf.main
    /usr/local/bin/ocrmypdf: 10: /usr/local/bin/ocrmypdf: Syntax error: "(" unexpected (expecting "then")
    

This is the executed code:

    
    
    pi@piscan:~ $ cat $(which ocrmypdf)
    #!/usr/bin/python3
    
    # -*- coding: utf-8 -*-
    import re
    import sys
    
    from ocrmypdf.main import run_pipeline
    
    if __name__ == '__main__':
        sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
        sys.exit(run_pipeline())
    


Answer: When you type `sh ocrmypdf` you ask the `sh` shell (probably `/bin/sh` which
is often a symlink to `/bin/bash` or `/bin/dash`) to interpret the `ocrmypdf`
file which is a _Python_ script, not a shell one.

So either run `python ocrmypdf` or `python $(which ocrmypdf)` or make the
`ocrmypdf` script executable. Then (on Linux at least)
[execve(2)](http://man7.org/linux/man-pages/man2/execve.2.html) will [start
the python interpreter](http://stackoverflow.com/questions/8967902/why-do-you-
need-to-put-bin-bash-at-the-beginning-of-a-script-file/8968514#8968514),
because of the [shebang](https://en.wikipedia.org/wiki/Shebang_%28Unix%29).

Of course, the `ocrmypdf` script should be in your
[`PATH`](https://en.wikipedia.org/wiki/PATH_%28variable%29)

And `crontab` jobs are not running in your desktop environment. So they don't
have access to your [X11](https://en.wikipedia.org/wiki/X_Window_System)
server [Xorg](https://en.wikipedia.org/wiki/X.Org_Server) (or to
[Wayland](https://en.wikipedia.org/wiki/Wayland_%28display_server_protocol%29),
if you are using it). You could explicitly set the `DISPLAY` variable for
that, but I don't recommend doing this.

