def askChoice(self,
                  question,
                  choices,
                  defaultValue=None,
                  sortChoices=False,
                  sortCallBack=None):
        """
        Ask the user the supplied question and list the choices to choose from, if no response given the default value is used

        @param question: question to be display to the user
        @param choices: list of choices for the user to choose from
        @param defaultValue: the value that will be used if no response given
        @param sortChoices: if True, choices will be sorted before showing them to the user
        @param sortCallBack: A callback function to handle the sorting of the choices (will only be used if sortChoices is set to True)

        @return:  selected choice
        """
        defaultValues = list()

        if defaultValue:
            defaultValues = [
                value.strip() for value in defaultValue.split(',')
            ]
            #we choose tolerant approach by just filtering out the invalid defaultValues entries, without raising an error
            defaultValues = filter(lambda value: value in choices,
                                   defaultValues)

        messageWihDefault = '%s%s' % (question,
                                      ('[%s]' %
                                       defaultValue) if defaultValue else '')
        message = "%(question)s\n\nMake a selection please: %(choices)s"
        index = 0
        formmattedChoices = ''

        if sortChoices:
            if not sortCallBack:
                choices.sort()
            else:
                sortCallBack(choices)

        for section in choices:
            index += 1
            formmattedChoices = "%s\n   %s: %s" % (formmattedChoices, index,
                                                   section)
        message = message % {
            'question': messageWihDefault,
            'choices': formmattedChoices
        }
        result = EasyDialogs.AskString(message)
        if result:
            selections = self._checkSelection(result, choices, False)
            result = choices[selections[0] - 1]
        else:
            if not defaultValues:
                raise ValueError(
                    "No/Invalid default value provided, please try again and select Nr"
                )
            result = defaultValues

        return result
示例#2
0
def GetType():
    """Ask user for distribution type"""
    while 1:
        d = Dlg.GetNewDialog(ID_DTYPE, -1)
        d.SetDialogDefaultItem(DTYPE_EXIST)
        d.SetDialogCancelItem(DTYPE_CANCEL)
        while 1:
            rv = ModalDialog(None)
            if rv in (DTYPE_EXIST, DTYPE_NEW, DTYPE_CANCEL):
                break
        del d
        if rv == DTYPE_CANCEL:
            sys.exit(0)
        if rv == DTYPE_EXIST:
            ##			macfs.SetFolder(':(MkDistr)')
            fss, ok = macfs.StandardGetFile('TEXT')
            if not ok:
                sys.exit(0)
            path = fss.as_pathname()
            basename = os.path.split(path)[-1]
            if basename[-8:] <> '.include':
                EasyDialogs.Message('That is not a distribution include file')
            else:
                return basename[:-8]
        else:
            name = EasyDialogs.AskString('Distribution name:')
            if name:
                return name
            sys.exit(0)
示例#3
0
 def askString(self, question, defaultValue=None, validator=None):
     message = '%s%s' % (question,
                         ('[%s]' % defaultValue) if defaultValue else '')
     result = EasyDialogs.AskString(message)
     import re
     if validator:
         if re.match(result, validator):
             if not result and defaultValue:
                 result = defaultValue
     return result
示例#4
0
 def _getsearchstring(self):
     # First we get the frontmost window
     front = self.getfrontwindow()
     if front and hasattr(front, 'getselectedtext'):
         text = front.getselectedtext()
         if text:
             return text
     # This is a cop-out. We should have disabled the menus
     # if there is no selection, but the can_ methods only seem
     # to work for Windows. Or not for the Help menu, maybe?
     text = EasyDialogs.AskString("Search documentation for", ok="Search")
     return text
示例#5
0
 def domenu_openURL(self, *args):
     ok = EasyDialogs.AskYesNoCancel(
         "Warning: by opening a non-standard database "
         "you are trusting the maintainer of it "
         "to run arbitrary code on your machine.",
         yes="OK",
         no="")
     if ok <= 0: return
     url = EasyDialogs.AskString("URL of database to open:",
                                 default=self.defaulturl,
                                 ok="Open")
     if url:
         self.opendoc(url)
示例#6
0
    def openother(self):
        import imp
        import EasyDialogs

        modname = EasyDialogs.AskString("Open module:")
        if modname:
            try:
                file, path, description = imp.find_module(modname)
            except ImportError:
                if modname in sys.builtin_module_names:
                    alerttext = "'%s' is a builtin module, which you can't edit." % modname
                else:
                    alerttext = "No module named '%s'." % modname
                raise W.AlertError, alerttext
            self.openscript(path, modname)
示例#7
0
 def readline(self):
     import EasyDialogs
     # A trick to make the input dialog box a bit more palatable
     if hasattr(sys.stdout, '_buf'):
         prompt = sys.stdout._buf
     else:
         prompt = ""
     if not prompt:
         prompt = "Stdin input:"
     sys.stdout.flush()
     rv = EasyDialogs.AskString(prompt)
     if rv is None:
         return ""
     rv = rv + "\n"  # readline should include line terminator
     sys.stdout.write(rv)  # echo user's reply
     return rv
示例#8
0
 def domenu_openbyname(self, *args):
     # Open a file by name. If the clipboard contains a filename
     # use that as the default.
     from Carbon import Scrap
     try:
         sc = Scrap.GetCurrentScrap()
         dft = sc.GetScrapFlavorData("TEXT")
     except Scrap.Error:
         dft = ""
     else:
         if not os.path.exists(dft):
             dft = ""
     filename = EasyDialogs.AskString("Open File Named:",
                                      default=dft,
                                      ok="Open")
     if filename:
         self.openscript(filename)
示例#9
0
def mac_getargs(args):
    inputs = []
    output = None
    commands = None
    ramprefix = None
    switched = 0

    import macfs
    import EasyDialogs
    if args[1:]:
        inputs = args[1:]
    else:
        fss, ok = macfs.StandardGetFile()
        if not ok:
            sys.exit(0)
        inputs = [fss.as_pathname()]
    dir = os.path.split(inputs[0])[0]
    os.chdir(dir)
    for i in range(len(inputs)):
        filename = inputs[i]
        if filename[:len(dir)] == dir:
            inputs[i] = filename[len(dir):]
    if len(inputs) == 1:
        dft = 'g2_' + inputs[0][1:]
        fss, ok = macfs.StandardPutFile("G2 output file", dft)
        if not ok:
            sys.exit(0)
        output = fss.as_pathname()
    fss, ok = macfs.StandardPutFile("Script output (cancel for text)", "Conversion script")
    if ok:
        commands = fss.as_pathname()
    reply = EasyDialogs.AskString("URL prefix for use in .ram file (cancel for no ram file)")
    if reply:
        ramprefix = reply
    reply = EasyDialogs.AskYesNoCancel("Create G2/GRiNS switch statements?")
    if reply > 0:
        switched = 1
    return inputs, output, commands, ramprefix, switched
示例#10
0
def AskString(message, value='', title='RoboFab'):
    """
	Returns entered string.
	Availability: FontLab, Macintosh
	"""
    if inFontLab:
        askString = _FontLabDialogAskString(message, value, title)
        askString.Run()
        v = askString.value
        if v is None:
            return None
        else:
            return v
    elif MAC:
        import EasyDialogs
        askString = EasyDialogs.AskString(message)
        if askString is None:
            return None
        if len(askString) == 0:
            return None
        else:
            return askString
    else:
        _raisePlatformError('GetString')
示例#11
0
OpenTiler Watermark
===================
This is a simple script which asks for the text and create a watermark.png file via Google Chart API

Created by Petr Pridal on 2010-01-26.
Copyright (c) 2010 Klokan Petr Pridal (www.klokan.cz). All rights reserved.
"""
import EasyDialogs
import sys, os

# Where is the executable file on the disk?
exepath = os.getcwd()
if hasattr(sys, "frozen"):
    exepath = os.path.dirname(sys.executable)

text = EasyDialogs.AskString(
    "Text for the watermark (following copyright mark)\nBest is to use your 'domain.org' name in lowercase\n(leave empty for no watermark):"
)

if text:
    print "http://chart.apis.google.com/chart?chst=d_text_outline&chld=FFFFFF|11|h|000000|b|©%20" + text
    import urllib2
    urlf = urllib2.urlopen(
        "http://chart.apis.google.com/chart?chst=d_text_outline&chld=FFFFFF|11|h|000000|b|%C2%A9%20"
        + urllib2.quote(text), 'rb')
    f = open(os.path.join(exepath, "watermark.png"), 'wb')
    f.write(urlf.read())
    f.close()
else:
    os.remove("watermark.png")
示例#12
0
def input_dialog(message):
    response = EasyDialogs.AskString(message, default='yourid')
    return response
示例#13
0
#
示例#14
0
from random import sample

if len(sys.argv) == 1:
    print("use `blindfiles.py --help` for command line options")
    if myos == 'win32':
        origdir = EasyDialogs.AskFolder(message="Choose directory with files to blind", windowTitle = "Choose Source")
    if myos == 'darwin':
        origdir = easygui.diropenbox(title="Choose directory with files to blind")
    if origdir is None: sys.exit()
    if myos == 'win32':
        blinddir = EasyDialogs.AskFolder(message="Choose an empty directory to place blinded files", windowTitle="Choose Destination")
    if myos == 'darwin':
        blinddir = easygui.diropenbox(title="Choose empty directory to place blinded files")
    if blinddir is None: sys.exit()
    if myos == 'win32':
        suffix = EasyDialogs.AskString(prompt='Enter file extensions to blind (e.g. `.jpg` or `.tif`)', default='.tif')
    if myos == 'darwin':
        suffix = easygui.enterbox(msg='Enter file extensions to blind (e.g. `.jpg` or `.tif`)', title='File extensions to blind', default='.tif', strip=True)
    if suffix is None: sys.exit()
elif len(sys.argv) < 3:
    print("")
    print("blindfiles.py assigns files in a directory tree a random name to reduce bias during subjective scoring procedures")
    print("original names and paths are stored in index.txt")
    print("blindfiles makes a blind copy and leaves the originals alone")
    print("usage: blindfiles.py <directory to blind (recursive)> <Directory to place blinded files (must not exist or be empty)> <file extensions to blind including dot>")
    print("")
    sys.exit()
else:
    origdir = sys.argv[1]
    blinddir = sys.argv[2]
    if len(sys.argv) > 3: suffix = sys.argv[3]
示例#15
0
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""
"""

__version__ = "$Id: EasyDialogs_AskString.py 1882 2009-01-04 15:38:33Z dhellmann $"
#end_pymotw_header

import EasyDialogs

response = EasyDialogs.AskString('What is your favorite color?',
                                 default='blue')
print 'RESPONSE:', response
示例#16
0
#                                                     #
#  Andrew MacPherson [ andrew <<at>> Paterva.com ]    #
#                                                     #
#######################################################
import os,sys,time,random
import EasyDialogs
from MaltegoTransform import *

me = MaltegoTransform();
me.parseArguments(sys.argv);
target = me.getValue();

portsFound = "";
fn = target + "-ports-" + str(random.randint(1000,9999)) + ".dat";  
defaultScanPorts = "22,21,25,80,443,3306";
scanPorts = EasyDialogs.AskString("Which TCP ports do you want to scan on " + target +"?",defaultScanPorts);
if (scanPorts is None):
	me.returnOutput();
	exit();
myentity = me.addEntity("IPAddress",target);
nmapCMD = "nmap -n -oG " + fn + " -p" + scanPorts + " -sS -PN " + target + ">"+fn+".stdout";
os.system(nmapCMD); 
try:
	if (os.path.exists(fn) == False):
		me.debug("File not found, please make sure another scan is not currently running. (windows limitation)");
		me.returnOutput();
		exit();
	f = open(fn)
        for line in f:
            if (line[:1] <> "#"):
            	fields = line.split("\t");
示例#17
0
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""
"""

__version__ = "$Id: EasyDialogs_AskString_too_long.py 1882 2009-01-04 15:38:33Z dhellmann $"
#end_pymotw_header

import EasyDialogs
import string

default = string.ascii_letters * 10
print 'len(default)=', len(default)
response = EasyDialogs.AskString('Enter a long string', default=default)
print 'len(response)=', len(response)
示例#18
0
"""AEservertest - Test AppleEvent server interface
示例#19
0
def composeMessageBody(pageURL):
    """Compose email's content."""
    extraText = EasyDialogs.AskString('Your message:', '')
    if extraText == None:
        raise RuntimeError, 'User cancelled.'
    return extraText + '\n\n<%s>' % pageURL