首页 > 解决方案 > 用于在脚本中修复 std I/O 重定向问题以添加 GUI 的 Python 想法

问题描述

我正在使用我在 github 上找到的一个小型 python 模块来编辑来自 pdf 的数据: https ://github.com/JoshData/pdf-redactor

它工作得很好,唯一的问题是它大多数是通过命令行调用来实现输入/输出重定向的,例如这是你在文件上调用它的方式:

python example.py < in.pdf > in-redacted.pdf

我正在寻找改变它的方法,以便输入/输出文件只是脚本本身内部的字符串/路径变量,这样就可以很容易地在它周围包装一个 GUI,就像现在我不确定的重定向一样如何让 GUI 输入参数。

我很困惑,因为当我运行print(sys.argv)它时只显示输入文件,这意味着重定向将参数删除为位置参数。

当我查看我正在使用的 python 库时,它非常硬编码以重定向标准输入/输出,所以我认为尝试重新编写它会是更困难的选择:

    # This is the function that performs redaction.

    if sys.version_info < (3,):
        if options.input_stream is None:
            options.input_stream = sys.stdin # input stream containing the PDF to redact
        if options.output_stream is None:
            options.output_stream = sys.stdout # output stream to write the new, redacted PDF to
    else:
        if options.input_stream is None:
            options.input_stream = sys.stdin.buffer # input byte stream containing the PDF to redact
        if options.output_stream is None:
            options.output_stream = sys.stdout.buffer # output byte stream to write the new, redacted PDF to

    from pdfrw import PdfReader, PdfWriter
    # Read the PDF.
    document = PdfReader(options.input_stream)

    # Modify its Document Information Dictionary metadata.
    update_metadata(document, options)

    # Modify its XMP metadata.
    update_xmp_metadata(document, options)

    if options.content_filters:
        # Build up the complete text stream of the PDF content.
        text_layer = build_text_layer(document, options)

        # Apply filters to the text stream.
        update_text_layer(options, *text_layer)

        # Replace page content streams with updated tokens.
        apply_updated_text(document, *text_layer)

    # Update annotations.
    update_annotations(document, options)

    # Write the PDF back out.
    writer = PdfWriter()
    writer.trailer = document
    writer.write(options.output_stream)

所以欢迎任何想法。

标签: pythonuser-interfaceinputstreamstdinoutputstream

解决方案


推荐阅读