Coder Social home page Coder Social logo

gooey's Introduction

Gooey

Turn (almost) any Python 3 Console Program into a GUI application with one line

Table of Contents


Quick Start

Installation instructions

The easiest way to install Gooey is via pip

pip install Gooey 

Alternatively, you can install Gooey by cloning the project to your local directory

git clone https://github.com/chriskiehl/Gooey.git

run setup.py

python setup.py install

Usage

Gooey is attached to your code via a simple decorator on whichever method has your argparse declarations (usually main).

from gooey import Gooey

@Gooey      <--- all it takes! :)
def main():
  parser = ArgumentParser(...)
  # rest of code

Different styling and functionality can be configured by passing arguments into the decorator.

# options
@Gooey(advanced=Boolean,          # toggle whether to show advanced config or not 
       language=language_string,  # Translations configurable via json
       auto_start=True,           # skip config screens all together
       target=executable_cmd,     # Explicitly set the subprocess executable arguments
       program_name='name',       # Defaults to script name
       program_description,       # Defaults to ArgParse Description
       default_size=(610, 530),   # starting size of the GUI
       required_cols=1,           # number of columns in the "Required" section
       optional_cols=2,           # number of columns in the "Optional" section
       dump_build_config=False,   # Dump the JSON Gooey uses to configure itself
       load_build_config=None,    # Loads a JSON Gooey-generated configuration
       monospace_display=False)   # Uses a mono-spaced font in the output screen
)
def main():
  parser = ArgumentParser(...)
  # rest of code

See: How does it Work section for details on each option.

Gooey will do its best to choose sensible widget defaults to display in the GUI. However, if more fine tuning is desired, you can use the drop-in replacement GooeyParser in place of ArgumentParser. This lets you control which widget displays in the GUI. See: GooeyParser

from gooey import Gooey, GooeyParser

@Gooey
def main():
  parser = GooeyParser(description="My Cool GUI Program!") 
  parser.add_argument('Filename', widget="FileChooser")
  parser.add_argument('Date', widget="DateChooser")
  ...

Examples

Gooey downloaded and installed? Great! Wanna see it in action? Head over the the Examples Repository to download a few ready-to-go example scripts. They'll give you a quick tour of all Gooey's various layouts, widgets, and features.

Direct Download

What is it?

Gooey converts your Console Applications into end-user-friendly GUI applications. It lets you focus on building robust, configurable programs in a familiar way, all without having to worry about how it will be presented to and interacted with by your average user.

Why?

Because as much as we love the command prompt, the rest of the world looks at it like an ugly relic from the early '80s. On top of that, more often than not programs need to do more than just one thing, and that means giving options, which previously meant either building a GUI, or trying to explain how to supply arguments to a Console Application. Gooey was made to (hopefully) solve those problems. It makes programs easy to use, and pretty to look at!

Who is this for?

If you're building utilities for yourself, other programmers, or something which produces a result that you want to capture and pipe over to another console application (e.g. *nix philosophy utils), Gooey probably isn't the tool for you. However, if you're building 'run and done,' around-the-office-style scripts, things that shovel bits from point A to point B, or simply something that's targeted at a non-programmer, Gooey is the perfect tool for the job. It lets you build as complex of an application as your heart desires all while getting the GUI side for free.

How does it work?

Gooey is attached to your code via a simple decorator on whichever method has your argparse declarations.

@Gooey
def my_run_func():
  parser = ArgumentParser(...)
  # rest of code

At run-time, it parses your Python script for all references to ArgumentParser. (The older optparse is currently not supported.) These references are then extracted, assigned a component type based on the 'action' they provide, and finally used to assemble the GUI.

Mappings:

Gooey does its best to choose sensible defaults based on the options it finds. Currently, ArgumentParser._actions are mapped to the following WX components.

Parser Action Widget Example
store TextCtrl
store_const CheckBox
store_true CheckBox
store_False CheckBox
version CheckBox
append TextCtrl
count DropDown                 
Mutually Exclusive Group RadioGroup
choice                                              DropDown

GooeyParser

If the above defaults aren't cutting it, you can control the exact widget type by using the drop-in ArgumentParser replacement GooeyParser. This gives you the additional keyword argument widget, to which you can supply the name of the component you want to display. Best part? You don't have to change any of your argparse code to use it. Drop it in, and you're good to go.

Example:

from argparse import ArgumentParser
....

def main(): 
    parser = ArgumentParser(description="My Cool Gooey App!")
    parser.add_argument('filename', help="name of the file to process") 

Given then above, Gooey would select a normal TextField as the widget type like this:

However, by dropping in GooeyParser and supplying a widget name, you can display a much more user friendly FileChooser

from gooey import GooeyParser
....

def main(): 
    parser = GooeyParser(description="My Cool Gooey App!")
    parser.add_argument('filename', help="name of the file to process", widget='FileChooser') 

Custom Widgets:

Widget Example
DirChooser, FileChooser, MultiFileChooser, FileSaver, MultiFileSaver

DateChooser/TimeChooser                                             

Please note that for both of these widgets the values passed to the application will always be in ISO format while localized values may appear in some parts of the GUI depending on end-user settings.

PasswordField

Listbox image
BlockCheckbox image
The default InlineCheck box can look less than ideal if a large help text block is present. BlockCheckbox moves the text block to the normal position and provides a short-form block_label for display next to the control. Use gooey_options.checkbox_label to control the label text
ColourChooser                                             

FilterableDropdown

IntegerField

DecimalField

Slider

Internationalization

Gooey is international ready and easily ported to your host language. Languages are controlled via an argument to the Gooey decorator.

@Gooey(language='russian')
def main(): 
    ... 

All program text is stored externally in json files. So adding new language support is as easy as pasting a few key/value pairs in the gooey/languages/ directory.

Thanks to some awesome contributors, Gooey currently comes pre-stocked with over 18 different translations!

Want to add another one? Submit a pull request!


Global Configuration

Just about everything in Gooey's overall look and feel can be customized by passing arguments to the decorator.

Parameter Summary
encoding Text encoding to use when displaying characters (default: 'utf-8')
use_legacy_titles Rewrites the default argparse group name from "Positional" to "Required". This is primarily for retaining backward compatibility with previous versions of Gooey (which had poor support/awareness of groups and did its own naive bucketing of arguments).
advanced Toggles whether to show the 'full' configuration screen, or a simplified version
auto_start Skips the configuration all together and runs the program immediately
language Tells Gooey which language set to load from the gooey/languages directory.
target Tells Gooey how to re-invoke itself. By default Gooey will find python, but this allows you to specify the program (and arguments if supplied).
suppress_gooey_flag Should be set when using a custom target. Prevent Gooey from injecting additional CLI params
program_name The name displayed in the title bar of the GUI window. If not supplied, the title defaults to the script name pulled from sys.argv[0].
program_description Sets the text displayed in the top panel of the Settings screen. Defaults to the description pulled from ArgumentParser.
default_size Initial size of the window
fullscreen start Gooey in fullscreen mode
required_cols Controls how many columns are in the Required Arguments section
⚠️ Deprecation notice: See Layout Customization for modern layout controls
optional_cols Controls how many columns are in the Optional Arguments section
⚠️ Deprecation notice: See Layout Customization for modern layout controls
dump_build_config Saves a json copy of its build configuration on disk for reuse/editing
load_build_config Loads a json copy of its build configuration from disk
monospace_display Uses a mono-spaced font in the output screen
⚠️ Deprecation notice: See Layout Customization for modern font configuration
image_dir Path to the directory in which Gooey should look for custom images/icons
language_dir Path to the directory in which Gooey should look for custom languages files
disable_stop_button Disable the Stop button when running
show_stop_warning Displays a warning modal before allowing the user to force termination of your program
force_stop_is_error Toggles whether an early termination by the shows the success or error screen
show_success_modal Toggles whether or not to show a summary modal after a successful run
show_failure_modal Toggles whether or not to show a summary modal on failure
show_restart_button Toggles whether or not to show the restart button at the end of execution
run_validators Controls whether or not to have Gooey perform validation before calling your program
poll_external_updates (Experimental!) When True, Gooey will call your code with a gooey-seed-ui CLI argument and use the response to fill out dynamic values in the UI (See: Using Dynamic Values)
use_cmd_args Substitute any command line arguments provided at run time for the default values specified in the Gooey configuration
return_to_config When True, Gooey will return to the configuration settings window upon successful run
progress_regex A text regex used to pattern match runtime progress information. See: Showing Progress for a detailed how-to
progress_expr A python expression applied to any matches found via the progress_regex. See: Showing Progress for a detailed how-to
hide_progress_msg Option to hide textual progress updates which match the progress_regex. See: Showing Progress for a detailed how-to
disable_progress_bar_animation Disable the progress bar
timing_options This contains the options for displaying time remaining and elapsed time, to be used with progress_regex and progress_expr. Elapsed / Remaining Time. Contained as a dictionary with the options show_time_remaining and hide_time_remaining_on_complete. Eg: timing_options={'show_time_remaining':True,'hide_time_remaining_on_complete':True}
show_time_remaining Disable the time remaining text see Elapsed / Remaining Time
hide_time_remaining_on_complete Hide time remaining on complete screen see Elapsed / Remaining Time
requires_shell Controls whether or not the shell argument is used when invoking your program. More info here
shutdown_signal Specifies the signal to send to the child process when the stop button is pressed. See Gracefully Stopping in the docs for more info.
navigation Sets the "navigation" style of Gooey's top level window.
Options:
TABBEDSIDEBAR
sidebar_title Controls the heading title above the SideBar's navigation pane. Defaults to: "Actions"
show_sidebar Show/Hide the sidebar in when navigation mode == SIDEBAR
body_bg_color HEX value of the main Gooey window
header_bg_color HEX value of the header background
header_height height in pixels of the header
header_show_title Show/Hide the header title
header_show_subtitle Show/Hide the header subtitle
footer_bg_color HEX value of the Footer background
sidebar_bg_color HEX value of the Sidebar's background
terminal_panel_color HEX value of the terminal's panel
terminal_font_color HEX value of the font displayed in Gooey's terminal
terminal_font_family Name of the Font Family to use in the terminal
terminal_font_weight Weight of the font (constants.FONTWEIGHT_NORMAL, constants.FONTWEIGHT_XXX)
terminal_font_size Point size of the font displayed in the terminal
error_color HEX value of the text displayed when a validation error occurs
richtext_controls Switch on/off the console support for terminal control sequences (limited support for font weight and color). Defaults to : False. See docs for additional details
menus Show custom menu groups and items (see: Menus
clear_before_run When true, previous output will be cleared from the terminal when running program again

Layout Customization

You can achieve fairly flexible layouts with Gooey by using a few simple customizations.

At the highest level, you have several overall layout options controllable via various arguments to the Gooey decorator.

show_sidebar=True show_sidebar=False navigation='TABBED' tabbed_groups=True

Grouping Inputs

By default, if you're using Argparse with Gooey, your inputs will be split into two buckets: positional and optional. However, these aren't always the most descriptive groups to present to your user. You can arbitrarily bucket inputs into logic groups and customize the layout of each.

With argparse this is done via add_argument_group()

parser = ArgumentParser()
search_group = parser.add_argument_group(
    "Search Options", 
    "Customize the search options"
)

You can add arguments to the group as normal

search_group.add_argument(
    '--query', 
    help='Base search string'
) 

Which will display them as part of the group within the UI.

Run Modes

Gooey has a handful of presentation modes so you can tailor its layout to your content type and user's level or experience.

Advanced

The default view is the "full" or "advanced" configuration screen. It has two different layouts depending on the type of command line interface it's wrapping. For most applications, the flat layout will be the one to go with, as its layout matches best to the familiar CLI schema of a primary command followed by many options (e.g. Curl, FFMPEG).

On the other side is the Column Layout. This one is best suited for CLIs that have multiple paths or are made up of multiple little tools each with their own arguments and options (think: git). It displays the primary paths along the left column, and their corresponding arguments in the right. This is a great way to package a lot of varied functionality into a single app.

Both views present each action in the Argument Parser as a unique GUI component. It makes it ideal for presenting the program to users which are unfamiliar with command line options and/or Console Programs in general. Help messages are displayed along side each component to make it as clear as possible which each widget does.

Setting the layout style:

Currently, the layouts can't be explicitly specified via a parameter (on the TODO!). The layouts are built depending on whether or not there are subparsers used in your code base. So, if you want to trigger the Column Layout, you'll need to add a subparser to your argparse code.

It can be toggled via the advanced parameter in the Gooey decorator.

@gooey(advanced=True)
def main():
    # rest of code   

Basic

The basic view is best for times when the user is familiar with Console Applications, but you still want to present something a little more polished than a simple terminal. The basic display is accessed by setting the advanced parameter in the gooey decorator to False.

@gooey(advanced=False)
def main():
    # rest of code  


No Config

No Config pretty much does what you'd expect: it doesn't show a configuration screen. It hops right to the display section and begins execution of the host program. This is the one for improving the appearance of little one-off scripts.

To use this mode, set auto_start=True in the Gooey decorator.

@Gooey(auto_start=True) 
def main (): 
    ... 


Menus

image

Added 1.0.2

You can add a Menu Bar to the top of Gooey with customized menu groups and items.

Menus are specified on the main @Gooey decorator as a list of maps.

@Gooey(menu=[{}, {}, ...])

Each map is made up of two key/value pairs

  1. name - the name for this menu group
  2. items - the individual menu items within this group

You can have as many menu groups as you want. They're passed as a list to the menu argument on the @Gooey decorator.

@Gooey(menu=[{'name': 'File', 'items: []},
             {'name': 'Tools', 'items': []},
             {'name': 'Help', 'items': []}])

Individual menu items in a group are also just maps of key / value pairs. Their exact key set varies based on their type, but two keys will always be present:

  • type - this controls the behavior that will be attached to the menu item as well as the keys it needs specified
  • menuTitle - the name for this MenuItem

Currently, three types of menu options are supported:

  • AboutDialog
  • MessageDialog
  • Link
  • HtmlDialog

About Dialog is your run-of-the-mill About Dialog. It displays program information such as name, version, and license info in a standard native AboutBox.

Schema

  • name - (optional)
  • description - (optional)
  • version - (optional)
  • copyright - (optional)
  • license - (optional)
  • website - (optional)
  • developer - (optional)

Example:

{
    'type': 'AboutDialog',
    'menuTitle': 'About',
    'name': 'Gooey Layout Demo',
    'description': 'An example of Gooey\'s layout flexibility',
    'version': '1.2.1',
    'copyright': '2018',
    'website': 'https://github.com/chriskiehl/Gooey',
    'developer': 'http://chriskiehl.com/',
    'license': 'MIT'
}

MessageDialog is a generic informational dialog box. You can display anything from small alerts, to long-form informational text to the user.

Schema:

  • message - (required) the text to display in the body of the modal
  • caption - (optional) the caption in the title bar of the modal

Example:

{
    'type': 'MessageDialog',
    'menuTitle': 'Information',
    'message': 'Hey, here is some cool info for ya!',
    'caption': 'Stuff you should know'
}

Link is for sending the user to an external website. This will spawn their default browser at the URL you specify.

Schema:

  • url - (required) - the fully qualified URL to visit

Example:

{
    'type': 'Link',
    'menuTitle': 'Visit Out Site',
    'url': 'http://www.example.com'
}

HtmlDialog gives you full control over what's displayed in the message dialog (bonus: people can copy/paste text from this one!).

Schema:

  • caption - (optional) the caption in the title bar of the modal
  • html - (required) the html you want displayed in the dialog. Note: only a small subset of HTML is supported. See the WX docs for more info.

Example:

{
    'type': 'HtmlDialog',
    'menuTitle': 'Fancy Dialog!',
    'caption': 'Demo of the HtmlDialog',
    'html': '''
    <body bgcolor="white">
        <img src=/path/to/your/image.png" /> 
        <h1>Hello world!</h1> 
        <p><font color="red">Lorem ipsum dolor sit amet, consectetur</font></p>
    </body>
    '''
}

A full example:

Two menu groups ("File" and "Help") with four menu items between them.

@Gooey(
    program_name='Advanced Layout Groups',
    menu=[{
        'name': 'File',
        'items': [{
                'type': 'AboutDialog',
                'menuTitle': 'About',
                'name': 'Gooey Layout Demo',
                'description': 'An example of Gooey\'s layout flexibility',
                'version': '1.2.1',
                'copyright': '2018',
                'website': 'https://github.com/chriskiehl/Gooey',
                'developer': 'http://chriskiehl.com/',
                'license': 'MIT'
            }, {
                'type': 'MessageDialog',
                'menuTitle': 'Information',
                'caption': 'My Message',
                'message': 'I am demoing an informational dialog!'
            }, {
                'type': 'Link',
                'menuTitle': 'Visit Our Site',
                'url': 'https://github.com/chriskiehl/Gooey'
            }]
        },{
        'name': 'Help',
        'items': [{
            'type': 'Link',
            'menuTitle': 'Documentation',
            'url': 'https://www.readthedocs.com/foo'
        }]
    }]
)

Dynamic Validation

⚠️ Note! This functionality is experimental and likely to be unstable. Its API may be changed or removed altogether. Feedback/thoughts on this feature is welcome and encouraged!

⚠️ See Release Notes for guidance on upgrading from 1.0.8 to 1.2.0

Before passing the user's inputs to your program, Gooey can optionally run a special pre-flight validation to check that all arguments pass your specified validations.

How does it work?

Gooey piggy backs on the type parameter available to most Argparse Argument types.

parser.add_argument('--some-number', type=int)
parser.add_argument('--some-number', type=float)

In addition to simple builtins like int and float, you can supply your own function to the type parameter to vet the incoming values.

def must_be_exactly_ten(value): 
    number = int(value) 
    if number == 10:
        return number
    else: 
        raise TypeError("Hey! you need to provide exactly the number 10!")
        
        
def main(): 
    parser = ArgumentParser()
    parser.add_argument('--ten', type=must_be_exactly_ten)

How to enable the pre-flight validation

By default, Gooey won't run the validation. Why? This feature is fairly experimental and does a lot of intense Monkey Patching behind the scenes. As such, it's currently opt-in.

You enable to validation by telling Gooey you'd like to subscribe to the VALIDATE_FORM event.

from gooey import Gooey, Events 

@Gooey(use_events=[Events.VALIDATE_FORM])
def main(): 
    ... 

Now, when you run Gooey, before it invokes your main program, it'll send a separate pre-validation check and record any issues raised from your type functions.

Full Code Example

from gooey import Gooey, Events
from argparse import ArgumentParser

def must_be_exactly_ten(value):
    number = int(value)
    if number == 10:
        return number
    else:
        raise TypeError("Hey! you need to provide exactly the number 10!")

@Gooey(program_name='Validation Example', use_events=[Events.VALIDATE_FORM])
def main():
    parser = ArgumentParser(description="Checkout this validation!")
    parser.add_argument('--ten', metavar='This field should be 10', type=must_be_exactly_ten)
    args = parser.parse_args()
    print(args)

Lifecycle Events and UI control

⚠️ Note! This functionality is experimental. Its API may be changed or removed altogether. Feedback on this feature is welcome and encouraged!

As of 1.2.0, Gooey now exposes coarse grain lifecycle hooks to your program. This means you can now take additional follow-up actions in response to successful runs or failures and even control the current state of the UI itself!

Currently, two primary hooks are exposed:

  • on_success
  • on_error

These fire exactly when you'd expect: after your process has completed.

Anatomy of an lifecycle handler:

Both on_success and on_error have the same type signature.

from typing import Mapping, Any, Optional
from gooey.types import PublicGooeyState  

def on_success(args: Mapping[str, Any], state: PublicGooeyState) -> Optional[PublicGooeyState]:
    """
    You can do anything you want in the handler including 
    returning an updated UI state for your next run!   
    """ 
    return state
    
def on_error(args: Mapping[str, Any], state: PublicGooeyState) -> Optional[PublicGooeyState]:
    """
    You can do anything you want in the handler including 
    returning an updated UI state for your next run!   
    """ 
    return state    
  • args This is the parsed Argparse object (e.g. the output of parse_args()). This will be a mapping of the user's arguments as existed when your program was invoked.
  • state This is the current state of Gooey's UI. If your program uses subparsers, this currently just lists the state of the active parser/form. Whatever updated version of this state you return will be reflected in the UI!

Attaching the handlers:

Handlers are attached when instantiating the GooeyParser.

parser = GooeyParser(
    on_success=my_success_handler,
    on_failure=my_failure_handler)

Subscribing to the lifecycle events

Just like Validation, these lifecycle events are opt-in. Pass the event you'd like to subscribe to into the use_events Gooey decorator argument.

from gooey import Gooey, Events 

@Gooey(use_events=[Events.ON_SUCCESS, Events.ON_ERROR])
def main(): 
    ... 

Showing Progress

Giving visual progress feedback with Gooey is easy! If you're already displaying textual progress updates, you can tell Gooey to hook into that existing output in order to power its Progress Bar.

For simple cases, output strings which resolve to a numeric representation of the completion percentage (e.g. Progress 83%) can be pattern matched and turned into a progress bar status with a simple regular expression (e.g. @Gooey(progress_regex=r"^progress: (\d+)%$")).

For more complicated outputs, you can pass in a custom evaluation expression (progress_expr) to transform regular expression matches as needed.

Output strings which satisfy the regular expression can be hidden from the console via the hide_progress_msg parameter (e.g. @Gooey(progress_regex=r"^progress: (\d+)%$", hide_progress_msg=True).

Regex and Processing Expression

@Gooey(progress_regex=r"^progress: (?P<current>\d+)/(?P<total>\d+)$",
       progress_expr="current / total * 100")

Program Output:

progress: 1/100
progress: 2/100
progress: 3/100
...

There are lots of options for telling Gooey about progress as your program is running. Checkout the Gooey Examples repository for more detailed usage and examples!

Elapsed / Remaining Time

Gooey also supports tracking elapsed / remaining time when progress is used! This is done in a similar manner to that of the project tqdm. This can be enabled with timing_options, the timing_options argument takes in a dictionary with the keys show_time_remaining and hide_time_remaining_on_complete. The default behavior is True for show_time_remaining and False for hide_time_remaining_on_complete. This will only work when progress_regex and progress_expr are used.

@Gooey(progress_regex=r"^progress: (?P<current>\d+)/(?P<total>\d+)$",
       progress_expr="current / total * 100",
       timing_options = {
        'show_time_remaining':True,
        'hide_time_remaining_on_complete':True,
    })

Customizing Icons

Gooey comes with a set of six default icons. These can be overridden with your own custom images/icons by telling Gooey to search additional directories when initializing. This is done via the image_dir argument to the Gooey decorator.

@Gooey(program_name='Custom icon demo', image_dir='/path/to/my/image/directory')
def main():
    # rest of program

Images are discovered by Gooey based on their filenames. So, for example, in order to supply a custom configuration icon, simply place an image with the filename config_icon.png in your images directory. These are the filenames which can be overridden:

  • program_icon.png
  • success_icon.png
  • running_icon.png
  • loading_icon.gif
  • config_icon.png
  • error_icon.png

Packaging

Thanks to some awesome contributors, packaging Gooey as an executable is super easy.

The tl;dr pyinstaller version is to drop this build.spec into the root directory of your application. Edit its contents so that the APPPNAME and name are relevant to your project and the pathex value points to your applications root, then execute pyinstaller -F --windowed build.spec to bundle your app into a ready-to-go executable.

Detailed step by step instructions can be found here.

Screenshots

Flat Layout Column Layout Success Screen Error Screen Warning Dialog
Custom Groups Tabbed Groups Tabbed Navigation Sidebar Navigation Input Validation

Wanna help?

Code, translation, documentation, or graphics? All pull requests are welcome. Just make sure to checkout the contributing guidelines first.

gooey's People

Contributors

arturmiller avatar azeirah avatar besslwalker avatar bilderbuchi avatar bje- avatar bryant1410 avatar changeling avatar chriskiehl avatar conradhilley avatar denarced avatar elad-eyal avatar eturkes avatar jpauwels avatar jschultz avatar jslirola avatar lrq3000 avatar ludovio avatar namujae avatar nathanrichard avatar neonbunny avatar rhkubiak avatar roshgar avatar rotu avatar sethmmorton avatar shiandow avatar shura1oplot avatar smacke avatar sodwyer avatar svisser avatar thiht avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gooey's Issues

IOError: Could not find english language file

Now #8 is fixed, I can install gooey on Ubuntu.

Running a very simple test program (code stolen from argparse docs example) gives me an error:

from gooey import Gooey
import argparse

@Gooey
def main():
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                       help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
                       const=sum, default=max,
                       help='sum the integers (default: find the max)')

    args = parser.parse_args()

python cli.py

Traceback (most recent call last):
  File "cli.py", line 1, in <module>
    from gooey import Gooey
  File "/usr/local/lib/python2.7/dist-packages/gooey/__init__.py", line 1, in <module>
    from gooey_decorator import Gooey
  File "/usr/local/lib/python2.7/dist-packages/gooey/gooey_decorator.py", line 16, in <module>
    from gooey.gui.base_window import BaseWindow
  File "/usr/local/lib/python2.7/dist-packages/gooey/gui/base_window.py", line 16, in <module>
    import header
  File "/usr/local/lib/python2.7/dist-packages/gooey/gui/header.py", line 10, in <module>
    from gooey import i18n
  File "/usr/local/lib/python2.7/dist-packages/gooey/i18n.py", line 37, in <module>
    _DICTIONARY = load(get_path(_LANG))
  File "/usr/local/lib/python2.7/dist-packages/gooey/i18n.py", line 24, in get_path
    raise IOError('Could not find {} language file'.format(language))
IOError: Could not find english language file

Looking in my /usr/local/lib/python2.7/dist-packages/gooey/languages, there's no .json files, only eng.py, init.py and their .pyc companions.

Something is still not going quite right with copying over the language files.

The path where I have the gooey download is /home/mb/Documents/python/Gooey, nothing exotic in there.

When I copy over the language files manually, it then complains that it can't find the images directory

OSError: [Errno 2] No such file or directory: '/usr/local/lib/python2.7/dist-packages/gooey/images'

After copying those over as well, it works pretty well 👍

Edit: found where the files get copied to: the files from gooey/images and gooey/languages get copied to /usr/local for some reason, instead of to /usr/local/lib/python2.7/dist-packages/gooey/...

Error running Gooey with argparse doc example

Hi,

I ran into this issue while just testing Gooey on the Python doc argparse example:

icon = os.path.join(image_dir, "icon.ico")
__init__ = os.path.join(image_dir, "__init__.py")
__init__ = os.path.join(image_dir, "__init__.pyc")
loader = os.path.join(image_dir, "loader.gif")
images = os.path.join(image_dir, "images.jpg")
settings2 = os.path.join(image_dir, "settings2.png")
alessandro_rei_checkmark = os.path.join(image_dir, "alessandro_rei_checkmark.png")
computer = os.path.join(image_dir, "computer.png")
computer3 = os.path.join(image_dir, "computer3.png")
computer2 = os.path.join(image_dir, "computer2.png")
returning resized image
returning resized image
returning resized image
Traceback (most recent call last):
  File "whyd2/testtt.py", line 18, in <module>
    main()
  File "/home/jtanay/.virtualenvs/whyd2/lib/python2.7/site-packages/gooey/gooey_decorator.py", line 59, in inner
    frame = BaseWindow(BodyPanel, client_app, params)
  File "/home/jtanay/.virtualenvs/whyd2/lib/python2.7/site-packages/gooey/gui/base_window.py", line 44, in __init__
    self._init_components(BodyPanel)
  File "/home/jtanay/.virtualenvs/whyd2/lib/python2.7/site-packages/gooey/gui/base_window.py", line 67, in _init_components
    self.config_panel = BodyPanel(self)
  File "/home/jtanay/.virtualenvs/whyd2/lib/python2.7/site-packages/gooey/gui/advanced_config.py", line 38, in __init__
    self._do_layout()
  File "/home/jtanay/.virtualenvs/whyd2/lib/python2.7/site-packages/gooey/gui/advanced_config.py", line 59, in _do_layout
    self.AddWidgets(container, self.components.required_args, add_space=True)
  File "/home/jtanay/.virtualenvs/whyd2/lib/python2.7/site-packages/gooey/gui/advanced_config.py", line 79, in AddWidgets
    widget_group = component.Build(parent=self)
  File "/home/jtanay/.virtualenvs/whyd2/lib/python2.7/site-packages/gooey/gui/components.py", line 38, in Build
    self._msg = self.CreateHelpMsgWidget(parent, self._action)
  File "/home/jtanay/.virtualenvs/whyd2/lib/python2.7/site-packages/gooey/gui/components.py", line 67, in CreateHelpMsgWidget
    base_text.SetLabelText(base_text.GetLabelText() + self.CreateNargsMsg(action))
AttributeError: 'StaticText' object has no attribute 'SetLabelText'

Am I missing something? I just reinstalled a fresh version of Gooey from github (pip install -U git+https://github.com/chriskiehl/Gooey.git). It might be a bug.

edit : I'm running py27 on a Fedora 20.

Let me know if I can help!

Thx

Support Qt

Adding Qt support would greatly increase your userbase :-).

Could not locate ArgumentParser statements in Main() ?

Hi all,

I am trying to run a very simple example with argparse and gooey (found here), just to start learning how I could use it.

import argparse
from gooey import Gooey

@Gooey
def Main():
    parser = argparse.ArgumentParser(description="Short sample app")

    parser.add_argument('-a', action="store_true", default=False)
    parser.add_argument('-b', action="store", dest="b")
    parser.add_argument('-c', action="store", dest="c", type=int)

    print parser.parse_args()

if __name__ == "__main__":
    Main()

Unfortunately, I already run through an error:

PS C:\Users\xx> python .\gooeyparstest.py

alessandro_rei_checkmark = os.path.join(image_dir, "alessandro_rei_checkmark.png")
computer = os.path.join(image_dir, "computer.png")
computer2 = os.path.join(image_dir, "computer2.png")
computer3 = os.path.join(image_dir, "computer3.png")
icon = os.path.join(image_dir, "icon.ico")
images = os.path.join(image_dir, "images.jpg")
settings2 = os.path.join(image_dir, "settings2.png")
__init__ = os.path.join(image_dir, "__init__.py")
__init__ = os.path.join(image_dir, "__init__.pyc")

Traceback (most recent call last):
  File ".\gooeyparstest.py", line 15, in <module>
    Main()
  File "C:\Anaconda\lib\site-packages\gooey-0.1.0-py2.7.egg\gooey\gooey_decorator.py", line 45, in inner
    parser = get_parser(module_path)
  File "C:\Anaconda\lib\site-packages\gooey-0.1.0-py2.7.egg\gooey\gooey_decorator.py", line 77, in get_parser
    'Could not locate ArgumentParser statements in Main().'
gooey.parser_exceptions.ParserError: Could not locate ArgumentParser statements in Main().
This is probably my fault :( Please checkout github.com/chriskiehl/gooey to file a bug!

Any ideas on why ArgumentParser cannot be found?

Thanks a lot

Error in `python': double free or corruption (fasttop): 0x00000000027dbd10

Hi there,

Finally decided to test this out on Linux. When I decide to invoke the script like so:

python imgur.py

I get an error like this:

Traceback (most recent call last):
  File "imgur.py", line 35, in <module>
    main()
  File "/usr/local/lib/python2.7/dist-packages/Gooey-0.1.0-py2.7.egg/gooey/gooey_decorator.py", line 85, in inner
    parser = get_parser(module_path)
  File "/usr/local/lib/python2.7/dist-packages/Gooey-0.1.0-py2.7.egg/gooey/gooey_decorator.py", line 114, in get_parser
    return source_parser.extract_parser(module_path)
  File "/usr/local/lib/python2.7/dist-packages/Gooey-0.1.0-py2.7.egg/gooey/source_parser.py", line 144, in extract_parser
    client_module = modules.load(module_source)
  File "/usr/local/lib/python2.7/dist-packages/Gooey-0.1.0-py2.7.egg/gooey/modules.py", line 32, in load
    os.remove(tmp_py_file)
OSError: [Errno 2] No such file or directory: '/usr/local/lib/python2.7/dist-packages/Gooey-0.1.0-py2.7.egg/gooey/d26058977d6da0ec2afd7fee0e636.py'

Invoking the script with sudo python imgur.py seems to fix that issue, but then when I decide to run it, the program crashes and I end up with something like this (emphasis on the last error to do with the double free corruption thingy):

(python:2533): Gtk-CRITICAL **: gtk_text_layout_real_invalidate: assertion 'layout->wrap_loop_count == 0' failed

(python:2533): Gtk-WARNING **: Invalid text buffer iterator: either the iterator is uninitialized, or the characters/pixbufs/widgets in the buffer have been modified since the iterator was created.
You must use marks, character numbers, or line numbers to preserve a position across buffer modifications.
You can apply tags and insert marks without invalidating your iterators,
but any mutation that affects 'indexable' buffer contents (contents that can be referred to by character offset)
will invalidate all outstanding iterators

(python:2533): Pango-CRITICAL **: pango_layout_index_to_pos: assertion 'layout != NULL' failed
*** Error in `python': double free or corruption (fasttop): 0x00000000027dbd10 ***

Not sure if this has something to do with the way I installed wxPython, perhaps? I had to follow these instructions to get it installed:

http://wiki.wxpython.org/InstallingOnUbuntuOrDebian

For DIST I used "natty" since that seemed to be the newest Ubuntu distro in that list. But even then, I'm using Linux Mint, not Ubuntu (even though Mint is based on Ubuntu).

This was my Gooey script I used:

https://github.com/chrispy645/gooey-imgur

Cheers

MANIFEST.in/setup.py README error

Your setup.py reads in README.md but is not included in your MANIFEST.in.

$ python setup.py sdist
$ cd dist
$ pip install Gooey-0.1.0.tar.gz
Unpacking ./Gooey-0.1.0.tar.gz
  Running setup.py (path:/var/folders/sg/4lw8t2_91mz6p8qdgl2q_h_80000gn/T/pip-fme_83-build/setup.py) egg_info for package from file:///Users/ctokheim/Desktop/Gooey/dist/Gooey-0.1.0.tar.gz
    Traceback (most recent call last):
      File "<string>", line 17, in <module>
      File "/var/folders/sg/4lw8t2_91mz6p8qdgl2q_h_80000gn/T/pip-fme_83-build/setup.py", line 5, in <module>
        with open('README.md') as readme:
    IOError: [Errno 2] No such file or directory: 'README.md'
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 17, in <module>

  File "/var/folders/sg/4lw8t2_91mz6p8qdgl2q_h_80000gn/T/pip-fme_83-build/setup.py", line 5, in <module>

    with open('README.md') as readme:

IOError: [Errno 2] No such file or directory: 'README.md'

----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1 in /var/folders/sg/4lw8t2_91mz6p8qdgl2q_h_80000gn/T/pip-fme_83-build
Storing debug log for failure in /Users/ctokheim/.pip/pip.log

It looks like either you could change your setup.py to use README.txt (not sure why you have two readme's?):

with open('README.txt') as readme:
    long_description = readme.read()

Or just include README.md in your MANIFEST.in file.

Python 3 compatibility

Hi, Gooey is a great idea, I was wondering is it possible to add Python 3 compatibility for this project?

get gooey working on os x

I observed that there was an OS X support feature in the TODO, but no issue in the tracker so I added one as I would like to hear when this will be available.

show_config results in UnboundLocalError

In the mockapplication module_with_no_argparse, build spec is shown to be referenced before assignment.

Traceback (most recent call last):
  File "C:\Python27\Lib\site-packages\gooey\gooey\mockapplications\module_with_no_argparse.py", line 18, in <module>
    main()
  File "C:\Python27\lib\site-packages\gooey-0.1.0-py2.7.egg\gooey\python_bindings\gooey_decorator.py", line 127, in inner
    frame = BaseWindow(BodyPanel, build_spec, params)
UnboundLocalError: local variable 'build_spec' referenced before assignment

WindowsError in removing temp files

WindowsError: [Error 2] The system cannot find the file specified: 'C:\\Python27\\lib\\site-packages\\gooey-0.1.0-
py2.7.egg\\gooey\\python_bindings\\da56848393418e7c55974af7edbbb2d2.pyc'

This just results from the inclusion of the decorator in any program

Fix the title to be less ambitious (at least mention that it's Python only)

Preamble: my reaction to the project

Turn (almost) any command line program into a full GUI application with one line

So my little C programs can have GUI for free? Wow.

setup.py

Python? Sad, no easy Windows portability.

Gooey is attached to your code via a simple decorator ...

So it's not just Gooey in Python, but also the target program nees to be in Python? So it's not that useful... But I still have a number of sys.argv-parsing Python programs, which I'll now automagically ...

parses it for all references to ArgumentParser

What is it? Probably a python battery for parsing command line arguments (never used that). So none of my programs can be "covered" by Gooey. Sad.

Proposals

I think the scope (Python programs using ArgumentParser) should be declared up front, not in the middle of README. (almost) any command line program is an exaggeration.

Or you will add a mode for arbitrary external programs (i.e. calling them with --help, parsing that human-readable (but structuted) description of possible command line arguments and values, then showing the window)?

@Gooey(config=False) throws exception

Steps to reproduce:

/main.py

from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
from gooey import Gooey

@Gooey(config=False)
def main():
    parser = ArgumentParser(description='Example', formatter_class=RawDescriptionHelpFormatter)
    args = parser.parse_args()
    print "hello, world"

if __name__ == '__main__':
    main()

Expected result when run:
Gooey should start up in console mode, without a configuration step.

Actual result:

Traceback (most recent call last):
  File "C:/.../main.py", line 12, in <module>
    main()
  File "C:\Python27\lib\site-packages\gooey\gooey_decorator.py", line 62, in inner
    frame.ManualStart()
  File "C:\Python27\lib\site-packages\gooey\gui\base_window.py", line 106, in ManualStart
    self._controller.ManualStart()
  File "C:\Python27\lib\site-packages\gooey\gui\controller.py", line 67, in ManualStart
    self._payload_runner.start()
AttributeError: 'Controller' object has no attribute '_payload_runner'

gooey.io

more a request feature than a bug, there is no site for the project, if you create a "gh-pages" branch I can push request this http://ludovio.github.io/Gooey/
you just have to select the theme you want

nargs optional arguments not able to add

:) sorry for all the reports but I think it just means you have an awesome plugin and people use it!

So when I specify the following argument:
parser.add_argument('gpx_files', type=argparse.FileType('r'), nargs='+', help='File containing GPX metadata that will be uploaded to the UV server.')
I get one input field in the required (which is correct because + means one or more) and an optional but empty fieldset. Is there a way to dynamically add an optional field? Like a [+] button.

Also, it seems that type=file gets a file input widget but argparse.FileType gets just a text input.

Python3 support

It would be great if gooey could run under python3. It's the future !

PyInstaller executable issue

After testing the application to work from source, I've built an executable:
pyinstaller.exe --onefile app.py

When I run the app.exe from the cmd, it prints the following error to the log:

Traceback (most recent call last):
File "", line 146, in
File "C:...\build\app\out00-PYZ.pyz\gooey.python_bindings.gooey_decorator", line 86, in inner
IOError: [Errno 2] No such file or directory: 'C:\Users...\AppData\Local\Temp_MEI108682\gooey_tmp\app.exe'

Does Gooey play well with PyInstaller or it hasn't been tested?

Add option to generate Python source code

This would greatly increase its usefulness, since now the generated Application is limited to what gooey does with the argparse code.

If it were to output the source code, a developer could then finetune it to his specific needs. I would personally use it as a boilerplate GUI for scripts I write.

What wrong

My script:

-- coding: utf8 --

import argparse
from gooey import Gooey

@gooey(advanced=True, program_name='Test', program_description='Test')
def main():
parser = argparse.ArgumentParser('Get my users')
parser.add_argument('-type', "--type", type=str, action='store', dest='type', help= "type Query")
parser.add_argument('-dst', "--datestart", type=str, action='store', dest='date_start', help= "from Date")
parser.add_argument('-dsp', "--datestop", type=str, action='store', dest='date_stop', help= "to Date")
parser.add_argument('-n',"--IDuser", type=str, action='store', dest='idu', help="IDuser")
parser.add_argument('-t',"--text", type=str, action='store', dest='text', help="find Text")
parser.add_argument('-f',"--file", type=str, action='store', dest='filepath', help="File Save")
args = parser.parse_args()
query_type = args.type
date_start=args.date_start
date_stop=args.date_stop
userid=args.idu
input_data = args.text
path_to_file = args.filepath
print path_to_file

if name == 'main':
main()

Errors:
alessandro_rei_checkmark = os.path.join(image_dir, "alessandro_rei_checkmark.png")
computer = os.path.join(image_dir, "computer.png")
computer2 = os.path.join(image_dir, "computer2.png")
computer3 = os.path.join(image_dir, "computer3.png")
icon = os.path.join(image_dir, "icon.ico")
images = os.path.join(image_dir, "images.jpg")
loader = os.path.join(image_dir, "loader.gif")
settings2 = os.path.join(image_dir, "settings2.png")
init = os.path.join(image_dir, "init.py")
init = os.path.join(image_dir, "init.pyc")
Traceback (most recent call last):
File "1.py", line 26, in
main()
File "c:\python27\lib\site-packages\gooey-0.1.0-py2.7.egg\gooey\gooey_decorator.py", line 59, in inner
frame = BaseWindow(BodyPanel, client_app, params)
File "c:\python27\lib\site-packages\gooey-0.1.0-py2.7.egg\gooey\gui\base_window.py", line 44, in init
self._init_components(BodyPanel)
File "c:\python27\lib\site-packages\gooey-0.1.0-py2.7.egg\gooey\gui\base_window.py", line 66, in _init_components
parent=self)
File "c:\python27\lib\site-packages\gooey-0.1.0-py2.7.egg\gooey\gui\header.py", line 32, in init
self._init_components(heading, subheading)
File "c:\python27\lib\site-packages\gooey-0.1.0-py2.7.egg\gooey\gui\header.py", line 45, in _init_components
self._subheader = wx.StaticText(self, label=subheading)
File "c:\python27\lib\site-packages\wx-3.0-msw\wx_controls.py", line 997, in init
controls.StaticText_swiginit(self,controls.new_StaticText(_args, *_kwargs))
TypeError: String or Unicode type required

Index out of range (Subparser issue?)

Traceback (most recent call last):
  File "lib/qidev.py", line 114, in <module>
    main()
  File "/usr/local/lib/python2.7/dist-packages/gooey/python_bindings/gooey_decorator.py", line 138, in inner
    frame = BaseWindow(BodyPanel, build_spec, params)
  File "/usr/local/lib/python2.7/dist-packages/gooey/gui/windows/base_window.py", line 36, in __init__
    self._init_components(BodyPanel)
  File "/usr/local/lib/python2.7/dist-packages/gooey/gui/windows/base_window.py", line 60, in _init_components
    self.config_panel = BodyPanel(self)
  File "/usr/local/lib/python2.7/dist-packages/gooey/gui/windows/advanced_config.py", line 39, in __init__
    self._do_layout()
  File "/usr/local/lib/python2.7/dist-packages/gooey/gui/windows/advanced_config.py", line 70, in _do_layout
    self.CreateComponentGrid(container, self.components.general_options, cols=2)
  File "/usr/local/lib/python2.7/dist-packages/gooey/gui/windows/advanced_config.py", line 90, in CreateComponentGrid
    hsizer.Add(widget.build(self), 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 10)
  File "/usr/local/lib/python2.7/dist-packages/gooey/gui/widgets/components2.py", line 30, in build
    return self.do_layout(parent)
  File "/usr/local/lib/python2.7/dist-packages/gooey/gui/widgets/components2.py", line 38, in do_layout
    core_widget_set = self.widget_pack.build(self.panel, self.data)
  File "/usr/local/lib/python2.7/dist-packages/gooey/gui/widgets/widget_pack.py", line 141, in build
    self.option_string = data['commands'][0]
IndexError: list index out of range

If it's helpful for debugging, all of the code for qidev.py is available on my github

Distributor ID: Ubuntu
Description: Ubuntu 14.10
Release: 14.10
Codename: utopic
Linux 3.16.0-30-generic #40-Ubuntu SMP Mon Jan 12 22:07:27 UTC 2015 i686 i686 i686 GNU/Linux

test.py throws an error

Invoking python ./test.py on the commandline gives me the following error

Traceback (most recent call last):
  File "./test.py", line 7, in <module>
    from gooey import gooey
  File "/home/mb/Documents/python/Gooey/gooey/__init__.py", line 1, in <module>
    from gooey_decorator import Gooey
  File "/home/mb/Documents/python/Gooey/gooey/gooey_decorator.py", line 16, in <module>
    from gooey.gui.base_window import BaseWindow
  File "/home/mb/Documents/python/Gooey/gooey/gui/base_window.py", line 16, in <module>
    import header
  File "/home/mb/Documents/python/Gooey/gooey/gui/header.py", line 10, in <module>
    from gooey import i18n
  File "/home/mb/Documents/python/Gooey/gooey/i18n.py", line 37, in <module>
    _DICTIONARY = load(get_path(_LANG))
  File "/home/mb/Documents/python/Gooey/gooey/i18n.py", line 35, in load
    'translation file is in the languages directory, ')
IOError: [Errno Language file not found. Make sure that your ] translation file is in the languages directory, 

Permission denied: '/Library/Python/2.7/site-packages/Gooey-0.1.0-py2.7.egg/gooey/_tmp/mockapp.py'

Using Gooey 0.1.0 on OSX Mavericks (10.9), I did a git clone from github, then installed:

git clone https://github.com/chriskiehl/Gooey.git
sudo python setup.py install

When I try to run the mockapp.py from the mockapplications directory, I got a permission error:

richs-mbp-8408:mockapplications richb$ python mockapp.py
['mockapp.py']
Traceback (most recent call last):
  File "mockapp.py", line 69, in <module>
    main()
  File "/Library/Python/2.7/site-packages/Gooey-0.1.0-py2.7.egg/gooey/python_bindings/gooey_decorator.py", line 86, in inner
    with open(filepath, 'w') as f:
IOError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/Gooey-0.1.0-py2.7.egg/gooey/_tmp/mockapp.py'

What can I do to fix the permissions? Thanks!

NB: I used sudo on the python setup.py install because without sudo, I get:

richs-mbp-8408:Gooey richb$ python setup.py install
running install
Checking .pth file support in /Library/Python/2.7/site-packages/
error: can't create or remove files in install directory

The following error occurred while trying to add or remove files in the
installation directory:

    [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/test-easy-install-10774.pth'

The installation directory you specified (via --install-dir, --prefix, or
the distutils default setting) was:

    /Library/Python/2.7/site-packages/

Perhaps your account does not have write access to this directory?  If the
installation directory is a system-owned directory, you may need to sign in
as the administrator or "root" account.  If you do not have administrative
access to this machine, you may wish to choose a different installation
directory, preferably one that is listed in your PYTHONPATH environment
variable.

For information on other options, you may wish to consult the
documentation at:

  https://pythonhosted.org/setuptools/easy_install.html

Please make the appropriate changes for your system and try again.

Can't open file loader.gif

On startup of any gooey app (including mockapp.py) I get the error message
"can't open file '/usr/local/Cellar/python/2.7.7/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Gooey-0.1.0-py2.7.egg/gooey/images/loader.gif" (error 2: No such file or directory)".

In the folder /usr/local/Cellar/python/2.7.7/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Gooey-0.1.0-py2.7.egg/gooey/images/ I have

__init__.py
__init__.pyc
alessandro_rei_checkmark.png
computer2.png
icon.ico
settings2.png
computer.png
computer3.png
images.jpg

It looks like loader.gif is not getting installed.

Have a "Restart!" button at the execution window for easy restart

Hi,

When we execute our job using UI and do some changes in linked file and then want to execute again.
We have to do following:

  1. Close the current window.
  2. Start script again.
  3. Provide all the arguments again (Very much annoying)
  4. Click 'Start'

Instead.

This can just have a "Restart" button that can run the job with last supplied parameters for ease.

Variables cannot be used when defining arguments.

The situation is hard to describe but basically,

@Gooey
def main():
    """Main"""
    bar = 'bar'
    parser = ArgumentParser(description='Desc')
    parser.add_argument('bar', help=('bar'))    ##################
    args = parser.parse_args()
    print(args)
    return True

works just fine but if you replace 'bar' with bar in the line flagged with '######', you get

Traceback (most recent call last):
  File "letscode.py", line 20, in <module>
    main()
  File "/home/sylvaindesodt/TmpCode/.tmp/letscode/letscode/Gooey/gooey/gooey_decorator.py", line 47, in inner
    parser = get_parser(module_path)
  File "/home/sylvaindesodt/TmpCode/.tmp/letscode/letscode/Gooey/gooey/gooey_decorator.py", line 76, in get_parser
    return source_parser.extract_parser(module_path)
  File "/home/sylvaindesodt/TmpCode/.tmp/letscode/letscode/Gooey/gooey/source_parser.py", line 99, in extract_parser
    return MonkeyParser(python_code)
  File "/home/sylvaindesodt/TmpCode/.tmp/letscode/letscode/Gooey/gooey/monkey_parser.py", line 27, in __init__
    self._parser_instance = self._build_argparser_from_client_source(source_code)
  File "/home/sylvaindesodt/TmpCode/.tmp/letscode/letscode/Gooey/gooey/monkey_parser.py", line 60, in _build_argparser_from_client_source
    eval(line)
  File "<string>", line 1, in <module>
NameError: name 'bar' is not defined

Can't copy 'computer3.png': doesn't exist or not a regular file.

sudo python setup.py install
running install
running build
running build_py
package init file 'gooey/images/__init__.py' not found (or not a regular file)
package init file 'gooey/images/__init__.py' not found (or not a regular file)
running install_lib
running install_data
error: can't copy 'computer3.png': doesn't exist or not a regular file

Changing images and languages to below

images = [os.path.join(imagepath, image) for image in os.listdir(imagepath)]

languages = [os.path.join(languagepath, lang)
            for lang in os.listdir(languagepath)
            if '.py' not in lang]

...
setup(
    ...
    data_files = [
        ('', images),
        ('', languages)
    ],
    ...
)

Fixes it. I'm not entirely sure why though. Are you developing on Windows? I'm running Ubuntu

IndentationError when block statement is in main() function

When I run the following MWE:

from gooey import Gooey, GooeyParser

@Gooey
def main():
    parser = GooeyParser(description="My Cool GUI Program!") 
    parser.add_argument('Filename', widget="FileChooser")
    parser.add_argument('--hello', action='store_true', default=False)
    args = parser.parse_args()

    print args.Filename
    if args.hello:
        print 'Hello!!'

if __name__ == '__main__':
    main()

I get the following error:

Traceback (most recent call last):
  File "gui.py", line 16, in <module>
    main()
  File "/usr/local/lib/python2.7/site-packages/gooey/python_bindings/gooey_decorator.py", line 118, in inner
    parser = get_parser(main_module_path)
  File "/usr/local/lib/python2.7/site-packages/gooey/python_bindings/gooey_decorator.py", line 161, in get_parser
    return source_parser.extract_parser(module_path)
  File "/usr/local/lib/python2.7/site-packages/gooey/python_bindings/source_parser.py", line 146, in extract_parser
    client_module = modules.load(module_source)
  File "/usr/local/lib/python2.7/site-packages/gooey/python_bindings/modules.py", line 21, in load
    return __import__(tmpfilename)
  File "/var/folders/9m/f1_73gtj5fq855hdxt9mb0nc0000gn/T/tmpP5Y9qh.py", line 9
    print 'Hello!!'
    ^
IndentationError: unexpected indent

I took a look at what is being passed to modules.load() and it is the following:

from gooey import Gooey, GooeyParser

def main():
    parser = GooeyParser(description="My Cool GUI Program!") 
    parser.add_argument('Filename', widget="FileChooser")
    parser.add_argument('--hello', action='store_true', default=False)
    return parser

        print 'Hello!!'

if __name__ == '__main__':
    main()

I understand that there is a fair amount of magic going on under the hood to get this to work, but it seems that this magic does not expect there to be any nested code structures in the main() function after the parser has been fully defined. Everything works as expected if there are no nested structures or if the nested structures are put into a separate function.

Could Gooey be updated to either handle this situation, or reflect this limitation in the README (if this limitation cannot be overcome)?

P.S. Amazing library!

Graphic work

What kind of graphics do you need?
Can you provide a list / table with, for each graphic elements:

  • Name
  • Description
  • Context (icon, illustration )
  • Format(s) and size(s)

Cannot install Gooey using pip.

When in try to install Gooey using pip ( pip install https://github.com/chriskiehl/Gooey.git ) I get this error:

Traceback (most recent call last):
  File "/home/tim/Workspace/thedotabot/task_queue/env/local/lib/python2.7/site-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/home/tim/Workspace/thedotabot/task_queue/env/local/lib/python2.7/site-packages/pip/commands/install.py", line 278, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "/home/tim/Workspace/thedotabot/task_queue/env/local/lib/python2.7/site-packages/pip/req.py", line 1197, in prepare_files
    do_download,
  File "/home/tim/Workspace/thedotabot/task_queue/env/local/lib/python2.7/site-packages/pip/req.py", line 1375, in unpack_url
    self.session,
  File "/home/tim/Workspace/thedotabot/task_queue/env/local/lib/python2.7/site-packages/pip/download.py", line 582, in unpack_http_url
    unpack_file(temp_location, location, content_type, link)
  File "/home/tim/Workspace/thedotabot/task_queue/env/local/lib/python2.7/site-packages/pip/util.py", line 627, in unpack_file
    and is_svn_page(file_contents(filename))):
  File "/home/tim/Workspace/thedotabot/task_queue/env/local/lib/python2.7/site-packages/pip/util.py", line 210, in file_contents
    return fp.read().decode('utf-8')
  File "/home/tim/Workspace/thedotabot/task_queue/env/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: invalid start byte

It also would be nice to publish this great project on PyPI. :)

Docstrings in source cause Gooey to crash

Specifically in source_parser when it attempts to read __dict__ from the string object. Test using a file with """Some content""" inline - I believe any multiline comments will exhibit the same behavior

The symptom AFAIK is an error emitted from modules when the post-guification code is attempted to be executed.from a source file that includes docstrings.

IOError: Could not find english language file after converting script to exe using py2exe

Hi,

I have made a small script that is using Gooey and when I converted it to a exe using py2exe or pythonInstaller I am getting following problem.

Traceback (most recent call last):
File "command_ui.py", line 1, in
File "gooey__init__.pyc", line 1, in
File "gooey\gooey_decorator.pyc", line 16, in
File "gooey\gui\base_window.pyc", line 16, in
File "gooey\gui\header.pyc", line 10, in
File "gooey\i18n.pyc", line 37, in
File "gooey\i18n.pyc", line 24, in get_path
IOError: Could not find english language file

Error running Gooey in virtualenv

I'm trying to get mock_argparse_example.py to run as is, but after pressing start I get this error:

Traceback (most recent call last):
  File "/home/vesa/venv/local/lib/python2.7/site-packages/Gooey-0.1.0-py2.7.egg/gooey/gui/windows/footer.py", line 152, in OnStartButton
    self._controller.OnStartButton(event, self)
  File "/home/vesa/venv/local/lib/python2.7/site-packages/Gooey-0.1.0-py2.7.egg/gooey/gui/controller.py", line 61, in OnStartButton
    self.RunClientCode(command)
  File "/home/vesa/venv/local/lib/python2.7/site-packages/Gooey-0.1.0-py2.7.egg/gooey/gui/controller.py", line 72, in RunClientCode
    p = subprocess.Popen(command, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

My current environment:

(venv)vesa@xubuntu ~> lsb_release -d
Description:    Ubuntu 14.04.1 LTS
(venv)vesa@xubuntu ~> python --version
Python 2.7.6
(venv)vesa@xubuntu ~> pip freeze
Gooey==0.1.0
Pillow==2.7.0
argparse==1.2.1
docx==0.2.4
jdcal==1.0
lxml==3.4.1
openpyxl==2.1.4
wsgiref==0.1.2
wxPython==2.8.12.1

Subparser support

Just tried Gooey - and it stumbled upon subparsers:

alessandro_rei_checkmark = os.path.join(image_dir, "alessandro_rei_checkmark.png")
computer = os.path.join(image_dir, "computer.png")
computer2 = os.path.join(image_dir, "computer2.png")
computer3 = os.path.join(image_dir, "computer3.png")
icon = os.path.join(image_dir, "icon.ico")
images = os.path.join(image_dir, "images.jpg")
loader = os.path.join(image_dir, "loader.gif")
settings2 = os.path.join(image_dir, "settings2.png")
__init__ = os.path.join(image_dir, "__init__.py")
Traceback (most recent call last):
  File "C:/development/work/avatar_hulk/gooey_subparser.py", line 153, in <module>
    sys.exit(main())
  File "C:\development\tools\venv\avatar\lib\site-packages\gooey\gooey_decorator.py", line 47, in inner
    parser = get_parser(module_path)
  File "C:\development\tools\venv\avatar\lib\site-packages\gooey\gooey_decorator.py", line 76, in get_parser
    return source_parser.extract_parser(module_path)
  File "C:\development\tools\venv\avatar\lib\site-packages\gooey\source_parser.py", line 99, in extract_parser
    return MonkeyParser(python_code)
  File "C:\development\tools\venv\avatar\lib\site-packages\gooey\monkey_parser.py", line 27, in __init__
    self._parser_instance = self._build_argparser_from_client_source(source_code)
  File "C:\development\tools\venv\avatar\lib\site-packages\gooey\monkey_parser.py", line 60, in _build_argparser_from_client_source
    eval(line)
  File "<string>", line 1, in <module>
NameError: name 'parameter_clients_parser' is not defined

I tweaked your example https://github.com/chriskiehl/Gooey/blob/master/gooey/mockapplications/example_argparse_souce_in_main.py a little bit to contain subparsers:

#!/usr/local/bin/python2.7
# encoding: utf-8
'''
bin.example_argparse_souce -- shortdesc

bin.example_argparse_souce is a description

It defines classes_and_methods

@author:     user_name

@copyright:  2013 organization_name. All rights reserved.

@license:    license

@contact:    user_email
@deffield    updated: Updated
'''

import sys
import os

from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
from gooey import Gooey

__all__ = []
__version__ = 0.1
__date__ = '2013-12-13'
__updated__ = '2013-12-13'

DEBUG = 0
TESTRUN = 0
PROFILE = 0


class CLIError(Exception):
  '''Generic exception to raise and log different fatal errors.'''

  def __init__(self, msg):
    super(CLIError).__init__(type(self))
    self.msg = "E: %s" % msg

  @property
  def __str__(self):
    return self.msg

  def __unicode__(self):
    return self.msg

@Gooey
def main(argv=None):  # IGNORE:C0111
  '''Command line options.'''

  if argv is None:
    argv = sys.argv
  else:
    sys.argv.extend(argv)

  program_name = os.path.basename(sys.argv[0])
  program_version = "v%s" % __version__
  program_build_date = str(__updated__)
  program_version_message = '%%(prog)s %s (%s)' % (program_version, program_build_date)
  program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
  program_license = '''%s

    Created by user_name on %s.
    Copyright 2013 organization_name. All rights reserved.

    Licensed under the Apache License 2.0
    http://www.apache.org/licenses/LICENSE-2.0

    Distributed on an "AS IS" basis without warranties
    or conditions of any kind, either express or implied.

USAGE
''' % (program_shortdesc, str(__date__))

  # Setup argument parser
  parser = ArgumentParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
  parser.add_argument("filename", help="filename")

  subparsers = parser.add_subparsers(help='sub-command -h for sub-command help', dest='subparser_name')
  parameter_parser = subparsers.add_parser("param", help='add some CRUD capabilities for Parameters ...')
  parameter_parser.add_argument('-c', '--create', action="store_true", help='creates a new parameter')

  enum_parser = subparsers.add_parser(ENUM, help='add some CRUD capabilities for Enumerations ...')
  enum_parser.add_argument('-a', '--add_enum_type', action="store_true", help='adds a new enumeration type')

  parser.add_argument("-r", "--recursive", dest="recurse", action="store_true",
                      help="recurse into subfolders [default: %(default)s]")
  parser.add_argument("-v", "--verbose", dest="verbose", action="count",
                      help="set verbosity level [default: %(default)s]")
  parser.add_argument("-i", "--include", action="append",
                      help="only include paths matching this regex pattern. Note: exclude is given preference over include. [default: %(default)s]",
                      metavar="RE")
  parser.add_argument("-m", "--mycoolargument", help="mycoolargument")
  parser.add_argument("-e", "--exclude", dest="exclude",
                      help="exclude paths matching this regex pattern. [default: %(default)s]", metavar="RE")
  parser.add_argument('-V', '--version', action='version')
  parser.add_argument('-T', '--tester', choices=['yes', 'no'])
  parser.add_argument(dest="paths", help="paths to folder(s) with source file(s) [default: %(default)s]",
                      metavar="path", nargs='+')

  # Process arguments
  args = parser.parse_args()

  paths = args.paths
  verbose = args.verbose
  recurse = args.recurse
  inpat = args.include
  expat = args.exclude

  if verbose > 0:
    print("Verbose mode on")
    if recurse:
      print("Recursive mode on")
    else:
      print("Recursive mode off")

  if inpat and expat and inpat == expat:
    raise CLIError("include and exclude pattern are equal! Nothing will be processed.")

  for inpath in paths:
    ### do something with inpath ###
    print(inpath)
  return 0


if __name__ == "__main__":
  if DEBUG:
    sys.argv.append("-h")
    #               sys.argv.append("-v")
    sys.argv.append("-r")
    main()
    sys.exit()
  if TESTRUN:
    import doctest

    doctest.testmod()
  if PROFILE:
    import cProfile
    import pstats

    profile_filename = 'bin.example_argparse_souce_profile.txt'
    cProfile.run('main()', profile_filename)
    statsfile = open("profile_stats.txt", "wb")
    p = pstats.Stats(profile_filename, stream=statsfile)
    stats = p.strip_dirs().sort_stats('cumulative')
    stats.print_stats()
    statsfile.close()
    sys.exit(0)
  sys.exit(main())

The code preparation in https://github.com/chriskiehl/Gooey/blob/master/gooey/code_prep.py does not play well with this (multiple subparsers with similar names).

Examples?

Decided to tinker with this a couple days ago and I'm really liking it. I wrote a simple example Gooey app (to present to fellow Pythoners) and then I thought, it would be nice if we had some sort of page here (i.e. a wiki page) that could showcase some examples made by the community or whatever. It would possibly help out those that are a bit new to argparse as well.

Not a particularly big deal though. :)

Offer python3 support via Tkinter and ttk

WX is not yet stable/ready for python3. Would dynamically pick the GUI backend based on what is available. I intend to pull request a proposal for this change. Would pave the way for other alternate GUI backends.

Issues with more complex argparse usage

As written, Gooey does not handle more complex ArgumentParser configurations. The two hitches I ran into are mutually exclusive groups, and directly populating custom classes. For example, I have the following code from a script I threw together for slicing out a geographically relevant subset from a larger dataset:

    parser = argparse.ArgumentParser(description='Extract a subset of data from a  directory structure')
    verbosity = parser.add_mutually_exclusive_group()
    verbosity.add_argument('-v', '--verbose', dest='verbose', action="store_true", help="Show more details")
    verbosity.add_argument('-q', '--quiet', dest='quiet', action="store_true", help="Only output on error")
    parser.add_argument('-i', '--indir', dest='indir', type=str, help="The top level of the input directory", required=True)
    parser.add_argument('-o', '--outdir', dest='outdir', type=str, help="Output directory for selected data (Note that this directory will be created if it does not already exist. If it already exists, it will be overwritten)", required=True)
    parser.add_argument('--sw', '--southwest', dest='swCorner', type=Coordinate.fromString, nargs=1, help='Southwest corner of selection region in integer degrees', metavar="{N|S}##{E|W}###", required=True)
    parser.add_argument('--ne', '--northeast', dest='neCorner', type=Coordinate.fromString, nargs=1, help='Northeast corner of selection region in integer degrees', metavar="{N|S}##{E|W}###", required=True)

Gooey immediately choked on the verbosity object. This appears to be due to the fact that monkey_parser.py is naievely evaling the input code, and expecting all lines to be simple add_argument calls. Removing the verbosity object and making those arguments on the base parser got around the issue, but now there is no way to ensure that one and only one of those switches is active. This seems like the sort of thing that would be good to support, perhaps as radio buttons.

The second hitch I ran into was with the last two arguments, which directly insert data into new instances of the custom Coordinate object, via Coordinate.fromString(). This too can be worked around by putting those arguments into strings, then calling fromString() after the fact, but that is sub-optimal, since it results in otherwise un-necessary extra complexity and code.

Have Gooey work with docopt

Really cool library.

Not so much an issue, more of a feature request: have Gooey work with or use docopt.

improve all the textbox

Improve all the textbox to support drag folder and file to the textbox, then the path of file/folder should be added to textbox

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.