Skip to content

added prompt #2

Description

@rlatowicz

This works on both Windows,
2023-11-05 20_05_48-cmd

and Linux,
2023-11-05 20_14_44-Ubuntu  Running  - Oracle VM VirtualBox

from ipykernel.kernelbase import Kernel
from subprocess import check_output
import os.path
import re
import signal

from pexpect import popen_spawn
import pexpect
import platform

def iswindows():
    return platform.system() == "Windows"

__version__ = "0.1.0"

class GSWrapper:
    """
    Wrap Ghostscript executable using pexpect
    """
    def __init__(self):
        """
        todo: config cmd can be 'gs', 'gs-X11', etc.
        """
        if iswindows():
            self.cmd = 'gswin64c -dNOSAFER' 
            self.p = popen_spawn.PopenSpawn(self.cmd)
        else:
            self.cmd = 'gs -dNOSAFER' 
            self.p = pexpect.spawn(self.cmd)

        # maybe input/output to gs is always 'ascii'?
        self.encoding = "utf8"

        pattern1 = b"GS>"
        self.p.expect(re.compile(pattern1))

        assert(self.p.after == b"GS>")

        
    def run(self, code):
        """
        Execute 'code' in session.

        newline is appended
        """
        prompt = re.compile(b'GS(>|<\d+>)')
        code = code + "\n"

        self.p.send(code)
        
        self.p.expect(prompt)

        before = self.p.before.decode(self.encoding)
        after = self.p.after.decode(self.encoding)
        
        if not iswindows():
            code = code.strip()
            before = before[len(code):]

        if len(before)==0:
            r = after
        else:
            r = before + after
            
        # .after is always the prompt itself. ?
        # eg:  b'GS>'
        #
        # could parse to get stack size
        # 'GS>', 'GS<1>', ...
        #

        return r.strip()

Note that I have added the -dNOSAFER option to cmd to allow scripts to run other scripts.

e.g.

(utils.ps) run

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions