简体   繁体   English

如何从命令行使用 gimpfu 运行 python 脚本?

[英]How to run python scripts using gimpfu from command line?

I'm trying to use functions of gimp 2.8.22 to convert a pdf to jpeg and i want to do that with a python script using the gimpfu library from my windows cmd (i have installed python 3.6.1).我正在尝试使用 gimp 2.8.22 的函数将 pdf 转换为 jpeg,我想使用我的 windows cmd 中的 gimpfu 库使用 python 脚本来做到这一点(我已经安装了 python 3.6.1)。

Right now, i't trying to do that with an example script:现在,我不想用示例脚本来做到这一点:

#!/usr/bin/env python

# Hello World in GIMP Python

from gimpfu import *

def hello_world(initstr, font, size, color) :
    # First do a quick sanity check on the font
    if font == 'Comic Sans MS' :
        initstr = "Comic Sans? Are you sure?"

    # Make a new image. Size 10x10 for now -- we'll resize later.
    img = gimp.Image(1, 1, RGB)

    # Save the current foreground color:
    pdb.gimp_context_push()

    # Set the text color
    gimp.set_foreground(color)

    # Create a new text layer (-1 for the layer means create a new layer)
    layer = pdb.gimp_text_fontname(img, None, 0, 0, initstr, 10,
                                   True, size, PIXELS, font)

    # Resize the image to the size of the layer
    img.resize(layer.width, layer.height, 0, 0)

    # Background layer.
    # Can't add this first because we don't know the size of the text layer.
    background = gimp.Layer(img, "Background", layer.width, layer.height,
                            RGB_IMAGE, 100, NORMAL_MODE)
    background.fill(BACKGROUND_FILL)
    img.add_layer(background, 1)

    # Create a new image window
    gimp.Display(img)
    # Show the new image window
    gimp.displays_flush()

    # Restore the old foreground color:
    pdb.gimp_context_pop()

register(
    "python_fu_hello_world",
    "Hello world image",
    "Create a new image with your text string",
    "Akkana Peck",
    "Akkana Peck",
    "2010",
    "Hello world (Py)...",
    "",      # Create a new image, don't work on an existing one
    [
        (PF_STRING, "string", "Text string", 'Hello, world!'),
        (PF_FONT, "font", "Font face", "Sans"),
        (PF_SPINNER, "size", "Font size", 50, (1, 3000, 1)),
        (PF_COLOR, "color", "Text color", (1.0, 0.0, 0.0))
    ],
    [],
    hello_world, menu="<Image>/File/Create")

main()

I try to run the script from my cmd like this:我尝试像这样从我的 cmd 运行脚本:

gimp-2.8 --no-interface --batch '(python_fu_hello_world RUN-NONINTERACTIVE "Hello" Arial 50 red)' -b '(gimp-quit 1)'

However, no matter what i do, i always geht the same error message:但是,无论我做什么,我总是收到相同的错误消息:

(gimp-2.8:1020): LibGimpBase-WARNING **: gimp-2.8: gimp_wire_read(): error (gimp-2.8:1020): LibGimpBase-WARNING **: gimp-2.8: gimp_wire_read(): 错误

edit: Ok, thanks.编辑:好的,谢谢。 I left out the interface statement and I also tried out the most simple example to figure out whats wrong:我省略了 interface 语句,并且还尝试了最简单的示例来找出问题所在:

#!/usr/bin/env python

# Hello World in GIMP Python

from gimpfu import *

def hello_world():
 gimp.message("Hello, GIMP world!\n")

register(
 "hello_world",
 'A simple Python-Fu "Hello, World" plug-in',
 'When run this plug-in prints "Hello, GIMP world!" in a dialog box.',
 "Tony Podlaski",
 "Tony Podlaski 2017. MIT License",
 "2017",
 "Hello World",
 "",
 [],
 [],
 hello_world,
 menu="<Image>/Filters/HelloWorld",
)

main()

The script actually works when i run it from Gimp itself, but when i try to run it from my cmd, Gimp opens with another cmd saying: Error: ( : 1) eval: unbound variable: hello_world当我从 Gimp 本身运行脚本时,该脚本实际上可以工作,但是当我尝试从我的 cmd 运行它时,Gimp 打开并显示另一个 cmd 说: Error: ( : 1) eval: unbound variable: hello_world

Does someone know what i'm missing here?有人知道我在这里缺少什么吗?

To run a python script you don't need to have it register as a plugin.要运行 python 脚本,您不需要将其注册为插件。 IMHO you should even avoid this, this unnecessarily pollutes Gimp's menus and procedure name space.恕我直言,您甚至应该避免这种情况,这会不必要地污染 Gimp 的菜单和程序名称空间。 Here is an example:下面是一个例子:

The batch script (saved as batch.py ):批处理脚本(另存为batch.py ):

#!/usr/bin/python
# -*- coding: iso-8859-15 -*-

import os, glob, sys, time
from gimpfu import *


def process(infile):
        print "Processing file %s " % infile
        image = pdb.gimp_file_load(infile, infile, run_mode=RUN_NONINTERACTIVE)
        drawable = image.active_layer

        print "File %s loaded OK" % infile
        pdb.plug_in_photocopy(image, drawable,8.,0.8,0.2,0.2)
        pdb.plug_in_cartoon(image, drawable, 7.,0.2)
        outfile=os.path.join('processed',os.path.basename(infile))
        outfile=os.path.join(os.path.dirname(infile),outfile)
        print "Saving to %s" % outfile
        pdb.file_jpeg_save(image, drawable, outfile, outfile, "0.5",0,1,0,"",0,1,0,0)
        print "Saved to %s" % outfile
        pdb.gimp_image_delete(image)


def run(directory):
        start=time.time()
        print "Running on directory \"%s\"" % directory
#   os.mkdir(os.path.join(directory,'processed'))
        for infile in glob.glob(os.path.join(directory, '*.jpg')):
                process(infile)
        end=time.time()
        print "Finished, total processing time: %.2f seconds" % (end-start)


if __name__ == "__main__":
        print "Running as __main__ with args: %s" % sys.argv

To call it:调用它:

gimp -idf --batch-interpreter python-fu-eval -b "import sys;sys.path=['.']+sys.path;import batch;batch.run('./images')" -b "pdb.gimp_quit(1)"

The parameters in slow-motion:慢动作参数:

  • -idf : work without user interface, and load neither data nor fonts (you may perhaps need to keep the fonts to load pdfs) -idf :在没有用户界面的情况下工作,既不加载数据也不加载字体(您可能需要保留字体以加载 pdf)
  • --batch-interpreter python-fu-eval : whatever follows -b is Python, not script-fu --batch-interpreter python-fu-eval : -b --batch-interpreter python-fu-eval内容是 Python,而不是 script-fu
  • "import sys;sys.path=['.']+sys.path;import batch;batch.run('./images')" : the code that we ask Gimp to execute, namely: "import sys;sys.path=['.']+sys.path;import batch;batch.run('./images')" :我们要求 Gimp 执行的代码,即:
    • import sys;sys.path=['.']+sys.path; : extend the import path to include the current directory : 扩展导入路径以包含当前目录
    • import batch; : import the file with our script, which is now in a directory which is part of the path. :使用我们的脚本导入文件,该文件现在位于作为路径一部分的目录中。
    • batch.run('./images') : call the run() function of the batch module we imported, giving it the name of a directory containing the images to process. batch.run('./images') :调用我们导入的batch模块的run()函数,为其指定包含要处理的图像的目录的名称。
  • -b "pdb.gimp_quit(1)" : another piece of python: exit when done. -b "pdb.gimp_quit(1)" :另一段 python:完成后退出。

Note how the command line cleverly uses double and single quotes to pass all parameters to Gimp and then to Python(*).请注意命令行如何巧妙地使用双引号和单引号将所有参数传递给 Gimp,然后传递给 Python(*)。 And yes, you can use forward slashes as file separators in Windows.是的,您可以在 Windows 中使用正斜杠作为文件分隔符。

To debug, matters are bit complicated in Windows because there is no always a stdout stream.要调试,Windows 中的事情有点复杂,因为并不总是有标准输出流。 Things that can help:可以提供帮助的事情:

  • remove the -i parameter temporarily so that you get the UI and perhaps a chance to see messages.暂时删除-i参数,以便您获得 UI 并可能有机会看到消息。
  • Add --verbose which makes Gimp start a secondary console window.添加--verbose使 Gimp 启动辅助控制台窗口。
  • There are other tricks to see messages listed here .查看此处列出的消息还有其他技巧。
  • You can also start Gimp normally and run your script from the Python-fu console (Filters>Python-fu>Console).您也可以正常启动 Gimp 并从 Python-fu 控制台(过滤器>Python-fu>控制台)运行您的脚本。 You will have to extend the path and import the file "manually".您将不得不扩展路径并“手动”导入文件。

(*) In a Linux/OSX shell one would do the opposite: single quotes for the shell, double quotes for Python. (*) 在 Linux/OSX shell 中,人们会做相反的事情:shell 的单引号,Python 的双引号。

Because the script you are using creates the image and then shows it in a window.... But you are calling Gimp with the --no-interface flag so the window is not shown.因为您正在使用的脚本创建图像,然后将其显示在窗口中......但是您正在使用--no-interface标志调用 Gimp,因此不会显示该窗口。

IMHO to convert from PDF to JPEG, ImageMagick's convert command would be a lot simpler.恕我直言,从 PDF 转换为 JPEG,ImageMagick 的convert命令会简单得多。

Also, in Windows Gimp comes with its own built-in Python 2.7 interpreter, so you have to write your Python code for that version, and there is no need to install another one.此外,在 Windows 中,Gimp 带有自己的内置 Python 2.7 解释器,因此您必须为该版本编写 Python 代码,而无需安装另一个。

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

相关问题 如何从命令行运行多个Python脚本? - How to run multiple Python scripts from command line? 如何使用 python 的命令行脚本在后台运行 python 程序? - How can I run a python program in the background using python's Command Line Scripts? 从Windows命令行运行Python脚本,未传递参数 - Run Python scripts from Windows command line, argument not passed 使用Enthought Canopy从Windows命令行运行python脚本 - Running python scripts from Windows command line using Enthought Canopy 如何使用python中的click制作命令行程序,该命令采用运行不同脚本的单独命令参数? - How do I make a command line program using click in python that takes separates command parameters that run different scripts? 从Python命令行调用Python时,为什么Python无法找到并运行我的脚本? - Why can't Python find and run my scripts when calling Python from Python command line? 如何使用tcl exec命令运行python脚本 - how to run python scripts using tcl exec command 如何从命令行运行 python function - How to run python function from command line 如何在python中将不同的脚本提交到命令行- - How to submit different scripts to the command line in python - python 中的命令行参数运行两个脚本之一 - Command line argument in python to run one of two scripts
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM