简体   繁体   English

无法通过sh / crontab启动python程序

[英]Not able to start python program via sh / crontab

I try to start a python program called ocrmypdf from a script or as a cronjob. 我尝试从脚本或cronjob启动一个名为ocrmypdf的python程序。

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())

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. 当您键入sh ocrmypdf您要求使用sh shell(可能是/bin/sh ,通常是/bin/bash/bin/dash的符号链接)来解释ocrmypdf文件,它是Python脚本,而不是shell脚本。

So either run python ocrmypdf or python $(which ocrmypdf) or make the ocrmypdf script executable. 因此,请运行python ocrmypdfpython $(which ocrmypdf)或使ocrmypdf脚本可执行。 Then (on Linux at least) execve(2) will start the python interpreter , because of the shebang . 然后(至少在Linux上),由于shebangexecve(2)启动python解释器

Of course, the ocrmypdf script should be in your PATH 当然, ocrmypdf脚本应该在您的PATH

And crontab jobs are not running in your desktop environment. 而且crontab作业不在您的桌面环境中运行。 So they don't have access to your X11 server Xorg (or to Wayland , if you are using it). 因此,他们无权访问您的X11服务器Xorg (如果正在使用,则无法访问Wayland )。 You could explicitly set the DISPLAY variable for that, but I don't recommend doing this. 您可以为此显式设置DISPLAY变量,但我不建议您这样做。

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

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