sys.stdin.readline.strip

Here are the examples of the python api sys.stdin.readline.strip taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

38 Examples 7

Example 1

Project: yumex
Source File: backend-launcher.py
View license
def dispatcher():
    write(":debug\tLAUNCHER: Ready for commands")
    write('#ready')
    try:
        line = sys.stdin.readline().strip('\n')
        if not line or line.startswith('#exit'):
            return False
        cmd, param = line.split('\t',2) # Dont blow up if more than 2 x \t instring
        rc = parse_command(cmd, param)
    except IOError, e:
        write(":error\tFatal error in backend launcher (can't read from sys.stdin)")
        write(":error\texception : %s %s " % ("", str(e)))
        rc = False
    except:
        write(":error\tFatal error in backend launcher")
        err, msg = (e.err, e.msg)
        write(":error\texception : %s %s " % (err, msg))
        rc = False
    return rc

Example 2

Project: inferno
Source File: fabfile.py
View license
@runs_once
def prepare_release():
    print "Please enter a release log message:"
    response = sys.stdin.readline().strip()
    if not response:
        print "Aborted. No log message"
        exit(1)
    tag_name = bump_version('patch', response)
    return tag_name

Example 3

Project: exabgp
Source File: tojson.py
View license
	def reader (self,myself):
		ok = True
		line = ''
		while True:
			line = sys.stdin.readline().strip()
			if ok:
				if not line:
					ok = False
					continue
			elif not line:
				break
			else:
				ok = True
			self.Q.append(line)
		os.kill(myself,signal.SIGTERM)

Example 4

Project: splunk-app-twitter
Source File: stream_tweets.py
View license
def main():
    session_key = sys.stdin.readline().strip()

    if len(session_key) == 0:
        sys.stderr.write(
            'Did not receive a session key from splunkd. Please enable ' +
            'passAuth in inputs.conf for this script.\n')
        exit(2)

    app_key, app_secret, oauth_token, oauth_token_secret = \
        get_oauth_settings(session_key)

    start(
        app_key=app_key,
        app_secret=app_secret,
        oauth_token=oauth_token,
        oauth_token_secret=oauth_token_secret)

Example 5

Project: inferno
Source File: fabfile.py
View license
def set_version():
    print "Please enter the new version no. (has to be in this format n.n.n):"
    version = sys.stdin.readline().strip()
    if not version:
        print "Aborted. No version"
        exit(1)
    print 'please eneter a message here for tagging the new release'
    message = sys.stdin.readline().strip()
    if not message:
        print "Aborted. No message"
        exit(1)
    with open(VERSION_PATH, 'w') as lib_info:
        lib_info.write("__version__ = %r\n" % version)
    tag_and_push(new_version, tag_name)
    return tag_name

Example 6

Project: codemod
Source File: base.py
View license
def _prompt(letters='yn', default=None):
    """
    Wait for the user to type a character (and hit Enter).  If the user enters
    one of the characters in `letters`, return that character.  If the user
    hits Enter without entering a character, and `default` is specified,
    returns `default`.  Otherwise, asks the user to enter a character again.
    """
    while True:
        try:
            input_text = sys.stdin.readline().strip()
        except KeyboardInterrupt:
            sys.exit(0)
        if input_text and input_text in letters:
            return input_text
        if default is not None and input_text == '':
            return default
        print('Come again?')

Example 7

Project: golismero
Source File: __init__.py
View license
def chatbots():
    import sys
    print 'Which chatbot would you like to talk to?'
    botcount = len(bots)
    for i in range(botcount):
        print '  %d: %s' % (i+1, bots[i][1])
    while True:
        print '\nEnter a number in the range 1-%d: ' % botcount,
        choice = sys.stdin.readline().strip()
        if choice.isdigit() and (int(choice) - 1) in range(botcount):
            break
        else:
            print '   Error: bad chatbot number'

    chatbot = bots[int(choice)-1][0]
    chatbot()

Example 8

Project: CloneGits
Source File: clonegits.py
View license
def make_github_agent(cli_args):
  ''' Create the Github object used
      to access their API.'''
  gh_agent = None
  if cli_args.token:
    gh_agent = Github(cli_args.token)
  else:
    user = cli_args.user
    if not user:
      print 'User:',
      user = sys.stdin.readline().strip()
    passw = getpass.getpass('Password:')
    gh_agent = Github(user, passw)
  return gh_agent

Example 9

Project: CloneGits
Source File: clonegits.py
View license
def make_github_agent(cli_args):
  ''' Create the Github object used
      to access their API.'''
  gh_agent = None
  if cli_args.token:
    gh_agent = Github(cli_args.token)
  else:
    user = cli_args.user
    if not user:
      print 'User:',
      user = sys.stdin.readline().strip()
    passw = getpass.getpass('Password:')
    gh_agent = Github(user, passw)
  return gh_agent

Example 10

Project: sycorax
Source File: get_access_token.py
View license
def main():
    print "Let's set up a character with Sycorax!"
    print
    token = get_request_token()
    url = AUTHORIZATION_URL + "?oauth_token=%s" % token.key
    print "1. Log in to Twitter as your character."
    print "2. Visit this URL: %s" % url
    print "3. Authorize Sycorax to access your character's account."
    print "4. Come back here, type in the PIN you got from Twitter, and hit Enter: "
    pin = int(sys.stdin.readline().strip())
    token, body = exchange_pin_for_access_token(pin, token)
    screen_name = urlparse.parse_qs(body)['screen_name'][0]
    output = dict(
        account=screen_name, twitter_token=token.key,
        twitter_secret=token.secret)
    print
    print "Success!"
    print 'Put something like this as your "authors" list in config.json:'
    print json.dumps([output])

Example 11

Project: sycorax
Source File: get_access_token.py
View license
def main():
    print "Let's set up a character with Sycorax!"
    print
    token = get_request_token()
    url = AUTHORIZATION_URL + "?oauth_token=%s" % token.key
    print "1. Log in to Twitter as your character."
    print "2. Visit this URL: %s" % url
    print "3. Authorize Sycorax to access your character's account."
    print "4. Come back here, type in the PIN you got from Twitter, and hit Enter: "
    pin = int(sys.stdin.readline().strip())
    token, body = exchange_pin_for_access_token(pin, token)
    screen_name = urlparse.parse_qs(body)['screen_name'][0]
    output = dict(
        account=screen_name, twitter_token=token.key,
        twitter_secret=token.secret)
    print
    print "Success!"
    print 'Put something like this as your "authors" list in config.json:'
    print json.dumps([output])

Example 12

Project: git-todo-py
Source File: todo.py
View license
def confirm():
    print "Are you sure? (y/N)"
    answer = sys.stdin.readline().strip()
    if answer == "y":
        return
    else:
        if verbose: print "You said: '%s' - nothing changed." % answer
        sys.exit()

Example 13

Project: git-todo-py
Source File: todo.py
View license
def confirm():
    print "Are you sure? (y/N)"
    answer = sys.stdin.readline().strip()
    if answer == "y":
        return
    else:
        if verbose: print "You said: '%s' - nothing changed." % answer
        sys.exit()

Example 14

Project: pyadb
Source File: whatsapp.py
View license
def get_whatsapp_root(adb,supath):
    
    tmp = getcwd()
    print "\n[+] Copying Whatsapp data folder"
    print "\t- Local destination [%s]: " % tmp ,
    destination = stdin.readline().strip()
    if destination == '':
        destination = tmp
    
    if not destination[-1:] == '/':
        destination += '/'
    destination += 'databases/' 
    
    try:
        mkdir(destination)
    except OSError,e:
        if e.errno == errno.EEXIST:
            pass
        else:
            return (False,e.args)
    except Exception,e:
        return (False,e.msg)

    tarname = '/sdcard/whatsapp_' + ''.join(random.choice(string.letters) for i in xrange(10)) + '.tar'
    print "\n[+] Creating remote tar file: %s" % tarname
    
    cmd = "%s -c 'tar -c /data/data/com.whatsapp -f %s'" % (supath,tarname)
    print "\t- Command: %s" % cmd
    adb.shell_command(cmd)
    
    print "\n[+] Retrieving remote file: %s" % tarname
    adb.get_remote_file(tarname, destination + '/' + basename(tarname))
    
    print "[+] Removing remote file: %s" % tarname
    cmd = 'su -c \'rm %s\'' % tarname    
    adb.shell_command(cmd)

    print "\n[+] Remote Whatsapp files from device memory are now locally accessible at \"%s%s\"\n" % (destination,basename(tarname))
    
    get_whatsapp_nonroot(adb)
    return (True,"")

Example 15

Project: pyadb
Source File: whatsapp.py
View license
def get_destination_path():
    """
    Creates and returns the path provided by the user
    """
    tmp = getcwd()
    print "\t- Local destination [%s]: " % tmp ,
    destination = stdin.readline().strip()
    if destination == '':
        destination = tmp
    
    if not destination[-1:] == '/':
        destination += '/' 
    
    try:
        mkdir(destination)
    except OSError,e:
        if e.errno == errno.EEXIST:
            pass
        else:
            print "\t- ERROR!: " , e.args
            return None
    except Exception,e:
        print "\t- ERROR!: " , e.mgs
        return None
    
    return destination

Example 16

Project: hg-git
Source File: run-tests.py
View license
def runone(options, test, count):
    '''returns a result element: (code, test, msg)'''

    def skip(msg):
        if options.verbose:
            log("\nSkipping %s: %s" % (testpath, msg))
        return 's', test, msg

    def fail(msg, ret):
        warned = ret is False
        if not options.nodiff:
            log("\n%s: %s %s" % (warned and 'Warning' or 'ERROR', test, msg))
        if (not ret and options.interactive
            and os.path.exists(testpath + ".err")):
            iolock.acquire()
            print "Accept this change? [n] ",
            answer = sys.stdin.readline().strip()
            iolock.release()
            if answer.lower() in "y yes".split():
                if test.endswith(".t"):
                    rename(testpath + ".err", testpath)
                else:
                    rename(testpath + ".err", testpath + ".out")
                return '.', test, ''
        return warned and '~' or '!', test, msg

    def success():
        return '.', test, ''

    def ignore(msg):
        return 'i', test, msg

    def describe(ret):
        if ret < 0:
            return 'killed by signal %d' % -ret
        return 'returned error code %d' % ret

    testpath = os.path.join(TESTDIR, test)
    err = os.path.join(TESTDIR, test + ".err")
    lctest = test.lower()

    if not os.path.exists(testpath):
            return skip("doesn't exist")

    if not (options.whitelisted and test in options.whitelisted):
        if options.blacklist and test in options.blacklist:
            return skip("blacklisted")

        if options.retest and not os.path.exists(test + ".err"):
            return ignore("not retesting")

        if options.keywords:
            fp = open(test)
            t = fp.read().lower() + test.lower()
            fp.close()
            for k in options.keywords.lower().split():
                if k in t:
                    break
                else:
                    return ignore("doesn't match keyword")

    if not lctest.startswith("test-"):
        return skip("not a test file")
    for ext, func, out in testtypes:
        if lctest.endswith(ext):
            runner = func
            ref = os.path.join(TESTDIR, test + out)
            break
    else:
        return skip("unknown test type")

    vlog("# Test", test)

    if os.path.exists(err):
        os.remove(err)       # Remove any previous output files

    # Make a tmp subdirectory to work in
    threadtmp = os.path.join(HGTMP, "child%d" % count)
    testtmp = os.path.join(threadtmp, os.path.basename(test))
    os.mkdir(threadtmp)
    os.mkdir(testtmp)

    port = options.port + count * 3
    replacements = [
        (r':%s\b' % port, ':$HGPORT'),
        (r':%s\b' % (port + 1), ':$HGPORT1'),
        (r':%s\b' % (port + 2), ':$HGPORT2'),
        ]
    if os.name == 'nt':
        replacements.append(
            (''.join(c.isalpha() and '[%s%s]' % (c.lower(), c.upper()) or
                     c in '/\\' and r'[/\\]' or
                     c.isdigit() and c or
                     '\\' + c
                     for c in testtmp), '$TESTTMP'))
    else:
        replacements.append((re.escape(testtmp), '$TESTTMP'))

    env = createenv(options, testtmp, threadtmp, port)
    createhgrc(env['HGRCPATH'], options)

    starttime = time.time()
    try:
        ret, out = runner(testpath, testtmp, options, replacements, env)
    except KeyboardInterrupt:
        endtime = time.time()
        log('INTERRUPTED: %s (after %d seconds)' % (test, endtime - starttime))
        raise
    endtime = time.time()
    times.append((test, endtime - starttime))
    vlog("# Ret was:", ret)

    killdaemons(env['DAEMON_PIDS'])

    skipped = (ret == SKIPPED_STATUS)

    # If we're not in --debug mode and reference output file exists,
    # check test output against it.
    if options.debug:
        refout = None                   # to match "out is None"
    elif os.path.exists(ref):
        f = open(ref, "r")
        refout = f.read().splitlines(True)
        f.close()
    else:
        refout = []

    if (ret != 0 or out != refout) and not skipped and not options.debug:
        # Save errors to a file for diagnosis
        f = open(err, "wb")
        for line in out:
            f.write(line)
        f.close()

    if skipped:
        if out is None:                 # debug mode: nothing to parse
            missing = ['unknown']
            failed = None
        else:
            missing, failed = parsehghaveoutput(out)
        if not missing:
            missing = ['irrelevant']
        if failed:
            result = fail("hghave failed checking for %s" % failed[-1], ret)
            skipped = False
        else:
            result = skip(missing[-1])
    elif ret == 'timeout':
        result = fail("timed out", ret)
    elif out != refout:
        if not options.nodiff:
            iolock.acquire()
            if options.view:
                os.system("%s %s %s" % (options.view, ref, err))
            else:
                showdiff(refout, out, ref, err)
            iolock.release()
        if ret:
            result = fail("output changed and " + describe(ret), ret)
        else:
            result = fail("output changed", ret)
    elif ret:
        result = fail(describe(ret), ret)
    else:
        result = success()

    if not options.verbose:
        iolock.acquire()
        sys.stdout.write(result[0])
        sys.stdout.flush()
        iolock.release()

    if not options.keep_tmpdir:
        shutil.rmtree(threadtmp, True)
    return result

Example 17

Project: py-vgdl
Source File: youtube_upload.py
View license
def run_main(parser, options, args, output=sys.stdout):
    """Run the main scripts from the parsed options/args."""
    if options.get_categories:
        output.write(" ".join(Youtube.get_categories().keys()) + "\n")
        return
    elif (options.create_playlist or options.add_to_playlist or 
         options.delete_from_playlist or options.update_metadata):
        required_options = ["email"]
    else:
        if not args:
            parser.print_usage()
            raise VideoArgumentMissing("Specify a video file to upload")
        required_options = ["email", "title", "category"]

    missing = [opt for opt in required_options if not getattr(options, opt)]
    if missing:
        parser.print_usage()
        raise OptionsMissing("Some required option are missing: %s" % ", ".join(missing))

    if options.password is None:
        password = getpass.getpass("Password for account <%s>: " % options.email)
    elif options.password == "-":
        password = sys.stdin.readline().strip()
    else:
        password = options.password
    youtube = Youtube(DEVELOPER_KEY)
    debug("Login to Youtube API: email='%s', password='%s'" %
          (options.email, "*" * len(password)))
    try:
        youtube.login(options.email, password, captcha_token=options.captcha_token,
                      captcha_response=options.captcha_response)
    except gdata.service.BadAuthentication:
        raise BadAuthentication("Authentication failed")
    except gdata.service.CaptchaRequired:
        token = youtube.service.captcha_token
        message = [
            "Captcha request: %s" % youtube.service.captcha_url,
            "Re-run the command with: --captcha-token=%s --captcha-response=CAPTCHA" % token,
        ]
        raise CaptchaRequired("\n".join(message))

    if options.create_playlist:
        title, description, private = tosize(options.create_playlist.split("|", 2), 3)
        playlist_uri = youtube.create_playlist(title, description, (private == "1"))
        debug("Playlist created: %s" % playlist_uri)
        output.write(playlist_uri+"\n")
    elif options.update_metadata:
        if not args:
            parser.print_usage()
            raise VideoArgumentMissing("Specify a video URL to upload")
        url = args[0]            
        updated = youtube.update_metadata(url, options.title, options.description)
        debug("Video metadata updated: %s" % url)
    elif options.add_to_playlist:
        for url in args:
            debug("Adding video (%s) to playlist: %s" % (url, options.add_to_playlist))
            video_id = get_video_id_from_url(url)
            youtube.add_video_to_playlist(video_id, options.add_to_playlist)
    elif options.delete_from_playlist:
        playlist = options.delete_from_playlist
        for url in args:
            video_id = get_video_id_from_url(url)
            debug("delete video (%s) from playlist: %s; video-id: %s" % 
              (url, playlist, video_id))
            youtube.delete_video_from_playlist(video_id, playlist)
    else:
      for index, video_path in enumerate(args):
        url = upload_video(youtube, options, video_path, len(args), index)
        output.write(url + "\n")

Example 18

View license
def VerifyOutputFile(output_dir, relative_path):
  """Verifies that the given output file path is valid.

  relative_path is relative to the output_dir directory.
  """

  # Makes sure the output file either doesn't exist or can be overwritten.
  output_file = os.path.join(output_dir, relative_path)
  if os.path.exists(output_file):
    # TODO([email protected]): The following user-interaction doesn't
    # work with automated processes.  We should provide a way for the
    # Makefile to force overwriting the files.
    print ('%s already exists in directory %s - overwrite it? (y/N) ' %
           (relative_path, output_dir))
    answer = sys.stdin.readline().strip()
    if answer not in ['y', 'Y']:
      print 'ABORTED.'
      sys.exit(1)

  # Makes sure the directory holding the output file exists; creates
  # it and all its ancestors if necessary.
  parent_directory = os.path.dirname(output_file)
  if not os.path.isdir(parent_directory):
    os.makedirs(parent_directory)

Example 19

View license
def VerifyOutputFile(output_dir, relative_path):
  """Verifies that the given output file path is valid.

  relative_path is relative to the output_dir directory.
  """

  # Makes sure the output file either doesn't exist or can be overwritten.
  output_file = os.path.join(output_dir, relative_path)
  if os.path.exists(output_file):
    # TODO([email protected]): The following user-interaction doesn't
    # work with automated processes.  We should provide a way for the
    # Makefile to force overwriting the files.
    print ('%s already exists in directory %s - overwrite it? (y/N) ' %
           (relative_path, output_dir))
    answer = sys.stdin.readline().strip()
    if answer not in ['y', 'Y']:
      print 'ABORTED.'
      sys.exit(1)

  # Makes sure the directory holding the output file exists; creates
  # it and all its ancestors if necessary.
  parent_directory = os.path.dirname(output_file)
  if not os.path.isdir(parent_directory):
    os.makedirs(parent_directory)

Example 20

Project: turbulenz_local
Source File: deploygame.py
View license
def _check_game(game):
    def log_issues(issues):
        for key, items in issues.iteritems():
            log('Issues in %s:' % key)
            for item in items:
                log('- %s:' % item[0])
                for value in item[1].get('errors', []):
                    error(value)
                for value in item[1].get('warnings', []):
                    warning(value)

    complete, issues = game.check_completeness()
    if not complete:
        log_issues(issues)
        exit(-1)

    issues, critical = game.validate_yaml()
    if issues:
        log_issues(issues)
        if critical:
            exit(-1)

        log('If you still want to deploy, the missing values will be replaced by default ones.')
        log('Deploy? (Y/N) ', False)
        if stdin.readline().strip()[0] not in 'yY':
            exit(-1)

Example 21

Project: parserator
Source File: manual_labeling.py
View license
def manualTagging(preds, valid_input_tags):
    tagged_sequence = []
    for token, predicted_tag in preds:
        while True:
            print('What is \'%s\' ? If %s hit return' % (token, predicted_tag))
            user_choice = sys.stdin.readline().strip()
            if user_choice == '' :
                tag = predicted_tag
                break
            elif user_choice in valid_input_tags :
                tag = valid_input_tags[user_choice]
                break
            elif user_choice in ('h', 'help', '?') :
                printHelp(valid_input_tags)
            elif user_choice == 'oops':
                print('No worries! Let\'s start over in labeling this string')
                tagged_sequence_redo = manualTagging(preds, valid_input_tags)
                return tagged_sequence_redo
            else:
                print("That is not a valid tag. Type 'help' to see the valid inputs")

        tagged_sequence.append((token, tag))
    return tagged_sequence

Example 22

Project: parserator
Source File: manual_labeling.py
View license
def naiveManualTag(raw_sequence, valid_input_tags):
    sequence_labels = []
    for token in raw_sequence:
        valid_tag = False
        while not valid_tag:
            print('What is \'%s\' ?' %token)
            user_input_tag = sys.stdin.readline().strip()
            if user_input_tag in valid_input_tags:
                valid_tag = True
            elif user_input_tag in ('h', 'help', '?') : 
                printHelp(valid_input_tags)
            elif user_input_tag == 'oops':
                print('No worries! Let\'s start over in labeling this string')
                sequence_labels_redo = naiveManualTag(raw_sequence, valid_input_tags)
                return sequence_labels_redo
            else:
                print("That is not a valid tag. Type 'help' to see the valid inputs")
            
        token_label = valid_input_tags[user_input_tag]
        sequence_labels.append((token, token_label))
    return sequence_labels

Example 23

Project: DIRAC
Source File: ProxyUpload.py
View license
def uploadProxy( params ):
  DIRAC.gLogger.info( "Loading user proxy" )
  proxyLoc = params.proxyLoc
  if not proxyLoc:
    proxyLoc = Locations.getDefaultProxyLocation()
  if not proxyLoc:
    return S_ERROR( "Can't find any proxy" )

  if params.onTheFly:
    DIRAC.gLogger.info( "Uploading proxy on-the-fly" )
    certLoc = params.certLoc
    keyLoc = params.keyLoc
    if not certLoc or not keyLoc:
      cakLoc = Locations.getCertificateAndKeyLocation()
      if not cakLoc:
        return S_ERROR( "Can't find user certificate and key" )
      if not certLoc:
        certLoc = cakLoc[0]
      if not keyLoc:
        keyLoc = cakLoc[1]

    DIRAC.gLogger.info( "Cert file %s" % certLoc )
    DIRAC.gLogger.info( "Key file  %s" % keyLoc )

    testChain = X509Chain()
    retVal = testChain.loadKeyFromFile( keyLoc, password = params.userPasswd )
    if not retVal[ 'OK' ]:
      passwdPrompt = "Enter Certificate password:"
      if params.stdinPasswd:
        userPasswd = sys.stdin.readline().strip( "\n" )
      else:
        userPasswd = getpass.getpass( passwdPrompt )
      params.userPasswd = userPasswd

    DIRAC.gLogger.info( "Loading cert and key" )
    chain = X509Chain()
    #Load user cert and key
    retVal = chain.loadChainFromFile( certLoc )
    if not retVal[ 'OK' ]:
      return S_ERROR( "Can't load %s" % certLoc )
    retVal = chain.loadKeyFromFile( keyLoc, password = params.userPasswd )
    if not retVal[ 'OK' ]:
      return S_ERROR( "Can't load %s" % keyLoc )
    DIRAC.gLogger.info( "User credentials loaded" )

    diracGroup = params.diracGroup
    if not diracGroup:
      result = chain.getCredentials()
      if not result['OK']:
        return result
      if 'group' not in result['Value']:
        return S_ERROR( 'Can not get Group from existing credentials' )
      diracGroup = result['Value']['group']
    restrictLifeTime = params.proxyLifeTime

  else:
    proxyChain = X509Chain()
    retVal = proxyChain.loadProxyFromFile( proxyLoc )
    if not retVal[ 'OK' ]:
      return S_ERROR( "Can't load proxy file %s: %s" % ( params.proxyLoc, retVal[ 'Message' ] ) )

    chain = proxyChain
    diracGroup = False
    restrictLifeTime = 0

  DIRAC.gLogger.info( " Uploading..." )
  return gProxyManager.uploadProxy( chain, diracGroup, restrictLifeTime = restrictLifeTime, rfcIfPossible = params.rfcIfPossible )

Example 24

Project: sala
Source File: __init__.py
View license
    def _simple_getpass(prompt=None):
        if prompt:
            print(prompt)
        return sys.stdin.readline().strip()

Example 25

Project: fMBT
Source File: fmbttizen-agent.py
View license
def read_cmd():
    return sys.stdin.readline().strip()

Example 26

Project: golismero
Source File: pchart.py
View license
def demo(choice=None, draw_parses=None, print_parses=None):
    """
    A demonstration of the probabilistic parsers.  The user is
    prompted to select which demo to run, and how many parses should
    be found; and then each parser is run on the same demo, and a
    summary of the results are displayed.
    """
    import sys, time
    from nltk import tokenize, toy_pcfg1, toy_pcfg2
    from nltk.parse import pchart

    # Define two demos.  Each demo has a sentence and a grammar.
    demos = [('I saw John with my telescope', toy_pcfg1),
             ('the boy saw Jack with Bob under the table with a telescope',
              toy_pcfg2)]

    if choice is None:
        # Ask the user which demo they want to use.
        print
        for i in range(len(demos)):
            print '%3s: %s' % (i+1, demos[i][0])
            print '     %r' % demos[i][1]
            print
        print 'Which demo (%d-%d)? ' % (1, len(demos)),
        choice = int(sys.stdin.readline().strip())-1
    try:
        sent, grammar = demos[choice]
    except:
        print 'Bad sentence number'
        return

    # Tokenize the sentence.
    tokens = sent.split()

    # Define a list of parsers.  We'll use all parsers.
    parsers = [
        pchart.InsideChartParser(grammar),
        pchart.RandomChartParser(grammar),
        pchart.UnsortedChartParser(grammar),
        pchart.LongestChartParser(grammar),
        pchart.InsideChartParser(grammar, beam_size = len(tokens)+1)   # was BeamParser
        ]

    # Run the parsers on the tokenized sentence.
    times = []
    average_p = []
    num_parses = []
    all_parses = {}
    for parser in parsers:
        print '\ns: %s\nparser: %s\ngrammar: %s' % (sent,parser,grammar)
        parser.trace(3)
        t = time.time()
        parses = parser.nbest_parse(tokens)
        times.append(time.time()-t)
        if parses: p = reduce(lambda a,b:a+b.prob(), parses, 0)/len(parses)
        else: p = 0
        average_p.append(p)
        num_parses.append(len(parses))
        for p in parses: all_parses[p.freeze()] = 1

    # Print some summary statistics
    print
    print '       Parser      Beam | Time (secs)   # Parses   Average P(parse)'
    print '------------------------+------------------------------------------'
    for i in range(len(parsers)):
        print '%18s %4d |%11.4f%11d%19.14f' % (parsers[i].__class__.__name__,
                                             parsers[i].beam_size,
                                             times[i],num_parses[i],average_p[i])
    parses = all_parses.keys()
    if parses: p = reduce(lambda a,b:a+b.prob(), parses, 0)/len(parses)
    else: p = 0
    print '------------------------+------------------------------------------'
    print '%18s      |%11s%11d%19.14f' % ('(All Parses)', 'n/a', len(parses), p)

    if draw_parses is None:
        # Ask the user if we should draw the parses.
        print
        print 'Draw parses (y/n)? ',
        draw_parses = sys.stdin.readline().strip().lower().startswith('y')
    if draw_parses:
        from nltk.draw.tree import draw_trees
        print '  please wait...'
        draw_trees(*parses)

    if print_parses is None:
        # Ask the user if we should print the parses.
        print
        print 'Print parses (y/n)? ',
        print_parses = sys.stdin.readline().strip().lower().startswith('y')
    if print_parses:
        for parse in parses:
            print parse

Example 27

Project: golismero
Source File: viterbi.py
View license
def demo():
    """
    A demonstration of the probabilistic parsers.  The user is
    prompted to select which demo to run, and how many parses should
    be found; and then each parser is run on the same demo, and a
    summary of the results are displayed.
    """
    import sys, time
    import nltk
    from nltk import tokenize
    from nltk.parse import ViterbiParser

    # Define two demos.  Each demo has a sentence and a grammar.
    demos = [('I saw the man with my telescope', nltk.toy_pcfg1),
             ('the boy saw Jack with Bob under the table with a telescope', nltk.toy_pcfg2)]

    # Ask the user which demo they want to use.
    print
    for i in range(len(demos)):
        print '%3s: %s' % (i+1, demos[i][0])
        print '     %r' % demos[i][1]
        print
    print 'Which demo (%d-%d)? ' % (1, len(demos)),
    try:
        snum = int(sys.stdin.readline().strip())-1
        sent, grammar = demos[snum]
    except:
        print 'Bad sentence number'
        return

    # Tokenize the sentence.
    tokens = sent.split()

    parser = ViterbiParser(grammar)
    all_parses = {}

    print '\nsent: %s\nparser: %s\ngrammar: %s' % (sent,parser,grammar)
    parser.trace(3)
    t = time.time()
    parses = parser.nbest_parse(tokens)
    time = time.time()-t
    if parses:
        average = reduce(lambda a,b:a+b.prob(), parses, 0)/len(parses)
    else:
        average = 0
    num_parses = len(parses)
    for p in parses:
        all_parses[p.freeze()] = 1

    # Print some summary statistics
    print
    print 'Time (secs)   # Parses   Average P(parse)'
    print '-----------------------------------------'
    print '%11.4f%11d%19.14f' % (time, num_parses, average)
    parses = all_parses.keys()
    if parses:
        p = reduce(lambda a,b:a+b.prob(), parses, 0)/len(parses)
    else: p = 0
    print '------------------------------------------'
    print '%11s%11d%19.14f' % ('n/a', len(parses), p)

    # Ask the user if we should draw the parses.
    print
    print 'Draw parses (y/n)? ',
    if sys.stdin.readline().strip().lower().startswith('y'):
        from nltk.draw.tree import draw_trees
        print '  please wait...'
        draw_trees(*parses)

    # Ask the user if we should print the parses.
    print
    print 'Print parses (y/n)? ',
    if sys.stdin.readline().strip().lower().startswith('y'):
        for parse in parses:
            print parse

Example 28

Project: econ-project-templates
Source File: processor.py
View license
def run():
	txt = sys.stdin.readline().strip()
	if not txt:
		# parent process probably ended
		sys.exit(1)
	[cmd, kwargs, cargs] = cPickle.loads(base64.b64decode(txt))
	cargs = cargs or {}

	ret = 1
	out, err, ex, trace = (None, None, None, None)
	try:
		proc = subprocess.Popen(cmd, **kwargs)
		try:
			out, err = proc.communicate(**cargs)
		except TimeoutExpired:
			if kwargs.get('start_new_session') and hasattr(os, 'killpg'):
				os.killpg(proc.pid, signal.SIGKILL)
			else:
				proc.kill()
			out, err = proc.communicate()
			exc = TimeoutExpired(proc.args, timeout=cargs['timeout'], output=out)
			exc.stderr = err
			raise exc
		ret = proc.returncode
	except Exception as e:
		exc_type, exc_value, tb = sys.exc_info()
		exc_lines = traceback.format_exception(exc_type, exc_value, tb)
		trace = str(cmd) + '\n' + ''.join(exc_lines)
		ex = e.__class__.__name__

	# it is just text so maybe we do not need to pickle()
	tmp = [ret, out, err, ex, trace]
	obj = base64.b64encode(cPickle.dumps(tmp))
	sys.stdout.write(obj.decode())
	sys.stdout.write('\n')
	sys.stdout.flush()

Example 29

Project: tryalgo
Source File: next_permutation.py
View license
    def _readstr():
        return stdin.readline().strip()

Example 30

Project: tryalgo
Source File: next_permutation.py
View license
    def _readstr():
        return stdin.readline().strip()

Example 31

Project: karaage
Source File: unlock_training_accounts.py
View license
    @django.db.transaction.atomic
    @tldap.transaction.commit_on_success
    def handle(self, *args, **options):
        verbose = int(options.get('verbosity'))
        training_prefix = getattr(settings, 'TRAINING_ACCOUNT_PREFIX', 'train')

        query = Person.active.all()
        query = query.filter(username__startswith=training_prefix)
        query = query.order_by('username')

        if options['number'] is not None:
            query = query[:options['number']]

        password = None
        if options['password']:
            password = sys.stdin.readline().strip()
        else:
            password = nicepass(6, 2)
            print("New password: %s" % password)

        for person in query.all():
            try:
                if password is not None:
                    if verbose > 1:
                        print("%s: Setting password" % person.username)
                    person.set_password(password)
                    # person.unlock() will call person.save()

                if verbose > 1:
                    print("%s: Unlocking" % person.username)
                person.unlock()

            except Exception as e:
                print("%s: Failed to unlock: %s" % (person.username, e))

Example 32

Project: karaage
Source File: unlock_training_accounts.py
View license
    @django.db.transaction.atomic
    @tldap.transaction.commit_on_success
    def handle(self, *args, **options):
        verbose = int(options.get('verbosity'))
        training_prefix = getattr(settings, 'TRAINING_ACCOUNT_PREFIX', 'train')

        query = Person.active.all()
        query = query.filter(username__startswith=training_prefix)
        query = query.order_by('username')

        if options['number'] is not None:
            query = query[:options['number']]

        password = None
        if options['password']:
            password = sys.stdin.readline().strip()
        else:
            password = nicepass(6, 2)
            print("New password: %s" % password)

        for person in query.all():
            try:
                if password is not None:
                    if verbose > 1:
                        print("%s: Setting password" % person.username)
                    person.set_password(password)
                    # person.unlock() will call person.save()

                if verbose > 1:
                    print("%s: Unlocking" % person.username)
                person.unlock()

            except Exception as e:
                print("%s: Failed to unlock: %s" % (person.username, e))

Example 33

Project: git-remote-dropbox
Source File: __init__.py
View license
def readline():
    """
    Read a line from standard input.
    """
    return sys.stdin.readline().strip()  # remove trailing newline

Example 34

Project: git-remote-dropbox
Source File: __init__.py
View license
def readline():
    """
    Read a line from standard input.
    """
    return sys.stdin.readline().strip()  # remove trailing newline

Example 35

View license
	def main_passpersist(self):
		"""
		Main function that handle SNMP's pass_persist protocol, called by
		the start method.
		Direct call is unnecessary.
		"""
		line = sys.stdin.readline().strip()
		if not line:
			raise EOFError()

		if 'PING' in line:
			print "PONG"
		elif 'getnext' in line:
			oid = self.cut_oid(sys.stdin.readline().strip())
			if oid is None:
				print "NONE"
			elif oid == "":
				# Fallback to the first entry
				print self.get_first()
			else:
				print self.get_next(oid)
		elif 'get' in line:
			oid = self.cut_oid(sys.stdin.readline().strip())
			if oid is None:
				print "NONE"
			else:
				print self.get(oid)
		elif 'set' in line:
			oid = sys.stdin.readline().strip()
			typevalue = sys.stdin.readline().strip()
			self.set(oid, typevalue)
		elif 'DUMP' in line: # Just for debbuging
			from pprint import pprint
			pprint(self.data)
		else:
			print "NONE"

		sys.stdout.flush()

Example 36

View license
	def main_passpersist(self):
		"""
		Main function that handle SNMP's pass_persist protocol, called by
		the start method.
		Direct call is unnecessary.
		"""
		line = sys.stdin.readline().strip()
		if not line:
			raise EOFError()

		if 'PING' in line:
			print "PONG"
		elif 'getnext' in line:
			oid = self.cut_oid(sys.stdin.readline().strip())
			if oid is None:
				print "NONE"
			elif oid == "":
				# Fallback to the first entry
				print self.get_first()
			else:
				print self.get_next(oid)
		elif 'get' in line:
			oid = self.cut_oid(sys.stdin.readline().strip())
			if oid is None:
				print "NONE"
			else:
				print self.get(oid)
		elif 'set' in line:
			oid = sys.stdin.readline().strip()
			typevalue = sys.stdin.readline().strip()
			self.set(oid, typevalue)
		elif 'DUMP' in line: # Just for debbuging
			from pprint import pprint
			pprint(self.data)
		else:
			print "NONE"

		sys.stdout.flush()

Example 37

Project: ndgrutedb
Source File: compile.py
View license
def test():
  """
  The testing function traverses all modules for compilation
  errrors
  """
  todo = None

  files = list(set(glob("*.py"))-set([__file__]))


  for fn in files :
    if fn == __file__:
      print "Skipping '%s' ..." % __file__

    print "compiling %s ..." % fn
    v = call(["python", fn, "-h"])
    if v == 0:
      print "=====> %s compile SUCCESS!\n" % fn
    else:
      print "**[ERROR]: %s compile FAILED!***\n\n" % fn
      print "Continue to run test on remaining scripts ? yes or no ?"

      todo = sys.stdin.readline().strip()
      if todo == "n" or todo == "no":
        print "[ERROR message]: Remaining tests not run. Please correct error & rerun the testscript."
        sys.exit(-1)

  if not todo:
    print "\n**Congratulations! Your modules all compiled successfully!**\n\n"
  else:
    print "\n**[ERROR message]: Tests completed with errors. Please check which scripts failed and rerun the test.**\n\n"

Example 38

Project: pyector
Source File: ConceptNetwork.py
View license
def main():
    import os
    from optparse import OptionParser

    usage = "usage: %prog [-h]"
    parser = OptionParser(usage=usage, version="%prog 0.1")
    parser.add_option("-f", "--file", dest="filename", default="conceptnetwork.pkl",
                      help="open the file as a Concept Network")
    (options, args) = parser.parse_args()

    filename = options.filename

    if os.path.exists(filename):
        f = open(filename)
        try:
            cn = pickle.load(f)
        finally:
            f.close()
    else:
        cn = ConceptNetwork()
    state = State(1)
    cn.addState(state)

    while True:
        line = sys.stdin.readline().strip()
        if sys.stdin.closed:
            break
        if line[:9] == "@addnode ":
            node = Node(line[9:])
            cn.addNode(node)
            print "Node \"%s\" added" % (line[9:])
        elif line[:9] == "@addlink ":
            params = line[9:].split()
            if len(params) == 2:
                try:
                    node1 = cn.getNode(params[0])
                except ConceptNetworkUnknownNode:
                    print "The node \"%s\" does not exist!" % (params[0])
                    continue
                try:
                    node2 = cn.getNode(params[1])
                except ConceptNetworkUnknownNode:
                    print "The node \"%s\" does not exist!" % (params[1])
                    continue
                print cn.addLink(node1, node2)
            elif len(params) == 3:
                node1 = cn.getNode(params[0])
                node2 = cn.getNode(params[1])
                node3 = cn.getNode(params[2])
                print cn.addLink(node1, node2, node3)
        elif line[:10] == "@shownodes":
            cn.showNodes()
        elif line[:10] == "@showlinks":
            cn.showLinks(1)
        elif line[:10] == "@activate ":
            params = line[10:].split()
            if len(params) == 1:
                state.setNodeActivationValue(100, params[0])
                nodeState = state.getNodeState(params[0])
                nodeState.resetAge()
            else:
                state.setNodeActivationValue(int(params[1]), params[0])
        elif line[:10] == "@showstate":
            state.showNodes()
        elif line[:10] == "@propagate":
            if len(line) > 10:
                nb = int(line[11:].strip())
                for i in range(0, nb):
                    cn.fastPropagateActivations(state)
            else:
                cn.fastPropagateActivations(state)
        elif line[:5] == "@save":
            # NOTE: the writing protocol must be the same than the reading one
            file = open(filename, "w")
            cn.dump(file, 0)
            file.close()
            file = open("state_1.pkl", "w")
            pickle.dump(state, file, 0)
            file.close()
            print "Concept Network saved in \"%s\"" % (filename)
        elif line.startswith("@quit"):
            return 0
        elif line[:5] == "@help":
            print """@help give this help