fhpythonutils / cli2gui Goto Github PK
View Code? Open in Web Editor NEWUse this module to convert a cli program to a gui
License: MIT License
Use this module to convert a cli program to a gui
License: MIT License
Hello Guys. I am new to Cli2gui and argparser and I am trying to create a GUI for my work. So for fileType (type), how can I set up a predefined dir to open as default rather than select every time?
on nix, pypandoc
pulls in these dependencies:
these 4 paths will be fetched (20.74 MiB download, 164.43 MiB unpacked):
/nix/store/5gm4rzsdd40i9ph97bxs5bwrfanmg11v-lua-5.3.6
/nix/store/7iyh4zqkmk8i6bpkdg99zrqhbckmy685-python3.9-pypandoc-1.7.2
/nix/store/sf07y0qw3bn11l7zj71kpadf65mffipb-pandoc-2.14.0.3-data
/nix/store/yvbr6knw00jl6wd7afcc8f9knl60h3hb-pandoc-2.14.0.3
feels a bit heavy. do we really need pandoc?
Currently it looks like Cli2Gui doesn't make use of the default
argument for argparse. It would be very nice if these showed up generated GUI.
# main.py
from cli2gui import Cli2Gui
import argparse
def run(args):
print(args.arg)
def main():
parser = argparse.ArgumentParser(description="this is an example parser")
parser.add_argument("--arg", type=str, default="foo", help="keyword arg")
parser.add_argument("--bool", action='store_true', default=True, help="boolean arg")
args = parser.parse_args()
run(args)
decorator_function = Cli2Gui(
run_function=run,
auto_enable=True,
)
gui = decorator_function(main)
if __name__ == "__main__":
gui()
Traceback:
Traceback (most recent call last):
File "C:\Users\delaplai\git\py\iosp\commands\gui.py", line 26, in
Click2Gui(run_function=hello)
File "C:\Users\delaplai\AppData\Local\Programs\Python\Python39\lib\site-packages\cli2gui\decorators.py", line 141, in Click2Gui
bSpec = BuildSpec(
"""Tests a simple parser
Program from https://click.palletsprojects.com/en/7.x/#documentation
"""
from future import annotations
import sys
from pathlib import Path
import click
THISDIR = str(Path(file).resolve().parent)
sys.path.insert(0, str(Path(THISDIR).parent.parent))
from cli2gui import Click2Gui
@click.command()
@click.option("--count", default=1, help="Number of greetings.")
@click.option("--name", prompt="Your name", help="The person to greet.")
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for _index in range(count):
click.echo("Hello %s!" % name)
Click2Gui(run_function=hello)
Interesting project, does this support Typer or plans to be supported as one of those CLI packages?
add a virtual terminal widget, so we can show the live stdout and stderr of the run
function
problem: when running the app without a terminal, then stdout/stderr are not visible
challenges:
run_function
or subprocess
example: capture stdout with io.TextIOBase
https://stackoverflow.com/questions/51527750/capture-print-output-from-multiple-threads-in-python
import threading
import time
import sys
import io
class demo_copy_stdout():
def __init__(self):
def run_function():
for i in range(0, 100):
print(*sys.argv, i)
time.sleep(1)
self.run_function = run_function
def main_function_wrapper(*argv):
sys.argv = argv # set arguments
# note: run_function takes no arguments
return self.run_function()
print("main_thread create")
self.main_thread = threading.Thread(target=main_function_wrapper, args=("toy.py", "hello",))
class CopyStdout(io.TextIOBase):
def __init__(self, target):
self.target = target
#self.stringio = io.StringIO()
def write(self, s):
writecount = self.target.write(s)
written = s[:writecount]
#self.stringio.write(written)
# TODO send to GUI
with open("stdout.txt", "a") as f:
f.write(written)
return writecount
print("copying stdout to tee.txt")
original_stdout = sys.stdout
sys.stdout = CopyStdout(sys.stdout)
print("main_thread start")
self.main_thread.start() # run
if True:
print("main_thread wait ...")
self.main_thread.join() # wait
print("main_thread done")
sys.stdout = original_stdout # stop copying stdout
x = demo_copy_stdout()
I'd really like to use cli2gui in a Jupyterhub project but I'm not sure if you're supporting that environment. I see that "web" is one of the GUI toolkits that's supported but perhaps that doesn't mean using Jupyterhub?
I've got a freshly built TLJH docker image from today's main head of https://github.com/jupyterhub/the-littlest-jupyterhub and have installed cli2gui by running "./pip install cli2gui" from within the /opt/tljh/user/bin directory of the running tljh docker instance. I've copied the contents of https://github.com/FHPythonUtils/Cli2Gui/blob/master/tests/argparse/test_10.py into a jupyterlab notebook cell (and commented out the top few file pathing stuff since cli2gui is already installed) . Upon running the cell, I get a tkinter error which suggests it's not detecting the Jupyter environment. The error is "TclError: no display name and no $DISPLAY environment variable." which makes a lot of sense since I'm not running this as a desktop app.
I'm hoping to get clarification that I can use your project within a Jupyter environment and if so, some pointers on how to get a working example.
I've found that this approach works well for detecting if a script is running under jupyter or not : https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook
why do we call open
here?
the run
function just needs the file path
path should be validated with os.path.exists(path)
Cli2Gui/cli2gui/application/pysimplegui2args.py
Lines 11 to 18 in 6b37803
in my case values[key] == ""
so open
throws FileNotFoundError(2, 'No such file or directory')
my parser looks like
parser = argparse.ArgumentParser()
extra_args.add_argument(
"--somefile",
type=argparse.FileType("r"),
required=False,
)
Cli2Gui/cli2gui/application/application.py
Lines 130 to 135 in be67588
TODO
comment in be67588. It's been assigned to @FredHappyface because they committed the code.When parser.add_subparsers()
is used, Cli2Gui fails with the message
[evan@blackbox picklecast] python /tmp/test.py
Traceback (most recent call last):
File "/tmp/test.py", line 30, in <module>
gui()
File "/home/evan/resources/venv3/lib/python3.10/site-packages/cli2gui/decorators.py", line 286, in inner
return callingFunction(*args, **kwargs)
File "/tmp/test.py", line 14, in main
args = parser.parse_args()
File "/home/evan/resources/venv3/lib/python3.10/site-packages/cli2gui/decorators.py", line 249, in runCli2Gui
buildSpec = createFromParser(
File "/home/evan/resources/venv3/lib/python3.10/site-packages/cli2gui/decorators.py", line 85, in createFromParser
return FullBuildSpec(**convertMap["self"][parser](selfParser), **buildSpec)
File "/home/evan/resources/venv3/lib/python3.10/site-packages/cli2gui/tojson/argparse2json.py", line 186, in convert
for _, subparser in iterParsers(parser):
File "/home/evan/resources/venv3/lib/python3.10/site-packages/cli2gui/tojson/argparse2json.py", line 42, in iterParsers
].choices.arg_items()
AttributeError: 'dict' object has no attribute 'arg_items'
#!/usr/bin/env python3
from cli2gui import Cli2Gui
import argparse
def run(args):
print(args.arg)
def main():
parser = argparse.ArgumentParser(description="this is an example parser")
parser.add_argument("arg", type=str, help="positional arg")
parser.add_subparsers()
args = parser.parse_args()
run(args)
decorator_function = Cli2Gui(
run_function=run,
auto_enable=True,
)
gui = decorator_function(main)
if __name__ == "__main__":
gui()
Ideally Cli2Gui would support these subparsers (perhaps as additional tabs in the GUI), but at least they could be ignored and not cause an exception.
A possible options it's to add "input ()" build-in function like readable option.
Instead of;
@cli2gui(argparse="argparse"...)
Can be possible put ...?
@cli2gui(argparse="inpu" ...)
Def func():
Var=imput ("...")
Many thanks in advance.
This is what's shown on the homepage / readme
Icon should be shown
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.