Beispiel #1
0
def start():
    """
    Create a virtual environment.
    """
    print("""
[1] with virtualenvwrapper / pyvenv
[2] with virtualenv
--------
[q] <<
    """.strip())
    while True:
        try:
            inp = raw_input("~~> ").strip()
        except (KeyboardInterrupt, EOFError):
            print()
            return
        if len(inp) == 0:
            continue
        elif inp == 'q':
            return
        elif inp == 'qq':
            common.my_exit(0)
        elif inp == '1':
            if mk_virtualenvwrapper() is DONE:
                return DONE
        elif inp == '2':
            if mk_virtualenv() is DONE:
                return DONE
        else:
            print("Hm?")
Beispiel #2
0
def get_python_ver():
    """
    Get Python version from the user: 2 or 3.

    The selected Python interpreter will be used in the created virt. env.
    """
    while True:
        try:
            inp = raw_input("~~~> ").strip()
        except (KeyboardInterrupt, EOFError):
            print()
            return
        if len(inp) == 0:
            continue
        elif inp == 'q':
            return
        elif inp == 'qq':
            common.my_exit(0)
        elif inp == '2':
            print("with Python 2")
            return 2
        elif inp == '3':
            print("with Python 3")
            return 3
        else:
            print("Hm?")
Beispiel #3
0
def main():
    show_menu()
    d_num = get_d_num(menu)
    d_word = get_d_word(menu)
    while True:
        try:
            inp = raw_input("~> ").strip()
        except (KeyboardInterrupt, EOFError):
            print()
            return
        if len(inp) == 0:
            continue
        elif inp == 'q':
            return
        elif inp == 'qq':
            common.my_exit(0)
        elif inp == 'm':
            show_menu()
            continue
        try:
            if inp.isdigit():
                val = d_num.get(int(inp))
            else:
                val = d_word.get(inp)
            if val is None:
                raise IndexError
        except IndexError:
            print("out of range...")
        else:
            start_app(val)
            show_menu()
Beispiel #4
0
def conferences():
    li = read_conferences_data()

    #    debug(li)
    #    return

    for index, e in enumerate(li[1:], start=1):
        print("({pos}) {id:20}[{url}]".format(pos=index, id=e[0], url=e[1]))
    print("[q] <<")
    while True:
        try:
            inp = raw_input("~~> ").strip()
        except (KeyboardInterrupt, EOFError):
            print()
            return None
        if len(inp) == 0:
            continue
        elif inp == "q":
            return
        elif inp == "qq":
            common.my_exit(0)
        try:
            index = int(inp)
            if index < 1:
                raise IndexError
            common.open_url(li[index][1])
            return
        except IndexError:
            print("out of range...")
        except ValueError:
            print("Wat?")
Beispiel #5
0
def radio_player():
    li, dic = read_radio_data()
    for index, e in enumerate(li[1:], start=1):
        print("({pos}) {id:20}[{url}]".format(pos=index, id=e[0], url=e[1]))
    print("[s] stop current radio")
    print("[q] <<")
    while True:
        try:
            inp = raw_input("~~> ").strip()
        except (KeyboardInterrupt, EOFError):
            print()
            return None
        if len(inp) == 0:
            continue
        elif inp == 'q':
            return
        elif inp == 's':
            radio(None, stop=True)
            return
        elif inp == 'qq':
            common.my_exit(0)
        try:
            index = int(inp)
            if index < 0:
                raise IndexError
            radio(li[index][1], id=li[index][0])
            return
        except IndexError:
            print("out of range...")
        except ValueError:
            print('Wat?')
Beispiel #6
0
def reddit():
    li = read_subreddits()
    #
    for index, subreddit in enumerate(li, start=1):
        print("[{i}] {sr}".format(i=index, sr=subreddit))
    print("[s] specify subreddit (without /r/)")
    print("[q] <<")
    while True:
        try:
            inp = raw_input("~~> ").strip()
        except (KeyboardInterrupt, EOFError):
            print()
            return None
        if len(inp) == 0:
            continue
        elif inp == 's':
            ok = enter_subreddit()
            if ok:
                return
        elif inp == 'q':
            return None
        elif inp == 'qq':
            my_exit(0)
        else:
            try:
                index = int(inp) - 1
                if index < 0:
                    raise IndexError
                open_subreddit(li[index])
                return
            except IndexError:
                print("out of range...")
            except ValueError:
                print('Wat?')
Beispiel #7
0
def process(d):
    t2k = OrderedDict()    # tag2keys
    #
    for k in d.iterkeys():
        o = d[k]
        if not(("doc" in o) and ("action" in o) and ("tags" in o)):
            print("Error: '{k}' must have doc, action, and tags.".format(k=k))
            my_exit(1)
        if len(o["doc"]) == 0:
            print("Error: '{k}' must have a valid doc.".format(k=k))
            my_exit(1)
        if len(o["tags"]) == 0:
            print("Error: '{k}' must have at least one tag.".format(k=k))
            my_exit(1)
        for t in o["tags"]:
            t = t.strip()
            if t[0] == '_':
                print("Error: the tag {tag} cannot start with an underscore.".format(tag=t))
                my_exit(1)
            if len(t) == 1:
                print("Error: the tag '{t}' in {k} is too short.".format(t=t, k=k))
                my_exit(1)
            if t in t2k:
                t2k[t].append(k)
            else:
                t2k[t] = [k]
    #
    return t2k
Beispiel #8
0
def perform_action(key):
    global last_key
    last_key = key
    #
    o = hdict[key]
    action = o["action"]
    verb = action[0]
    if verb == 'cat':
        cat(action[1], o)
    elif verb == 'open_url':
        open_url(action[1], o["doc"])
    else:
        print("Error: unknown action: {a}.".format(a=verb))
        my_exit(1)
Beispiel #9
0
def username_password():
    """
    Generate username and password.

    This is used for online registrations.
    The function has a static variable called
    "password", set in init().
    If you provide your email in the file
    email.txt, you can also copy it to the
    clipboards.
    """
    username = userpass.get_username()
    password = userpass.get_password(length=12)
    try:
        email = open("{root}/email.txt".format(root=cfg.ROOT)).read().strip()
    except IOError:
        email = None

    print("""
[1] {u:21} (username, copy to clipboard)
[2] {p:21} (password, copy to clipboard)
[3] {e:21} (email, copy to clipboard)
[q] <<
""".strip().format(u=username, p=password, e=email))
    while True:
        try:
            inp = raw_input("~~> ").strip()
        except (KeyboardInterrupt, EOFError):
            print()
            return
        if len(inp) == 0:
            continue
        elif inp == 'q':
            return
        elif inp == 'qq':
            common.my_exit(0)
        elif inp == '1':
            text_to_clipboards(username, prefix="username")
        elif inp == '2':
            text_to_clipboards(password, prefix="password")
            username_password.password = password
        elif inp == '3':
            if email:
                text_to_clipboards(email, prefix="email")
            else:
                print("Warning! You have no email specified.")
                print("Tip: create an email.txt file in the PrimCom folder.")
        else:
           print('Wat?')
Beispiel #10
0
def perform_action(key, search_term=""):
    global last_key
    last_key = key
    #
    o = hdict[key]
    action = o["action"]
    verb = action[0]
    if verb == 'cat':
        fname = fname_to_abs(action[1])
        colored_line_numbers.cat(fname, o, search_term)
        process_extras(fname, o)
    elif verb == 'open_url':
        open_url(action[1], o["doc"])
    else:
        print("Error: unknown action: {a}.".format(a=verb))
        my_exit(1)
Beispiel #11
0
def pid_alert():
    text = """
(1) ps
(2) adjust alert volume
(3) set pid to watch (add:<pid>, remove:<pid>)
(4) list of watched processes (d)
[m] this menu
[q] <<
""".strip()
    print(text)
    while True:
        try:
            inp = raw_input("~~> ").strip()
        except (KeyboardInterrupt, EOFError):
            print()
            return None
        if len(inp) == 0:
            continue
        elif inp == 'q':
            return
        elif inp == 'qq':
            my_exit(0)
        elif inp == 'm':
            print(text)
        elif inp.startswith('!'):
            cmd = inp[1:]
            os.system(cmd)
        elif inp in ('1', 'ps'):
            os.system("ps ux")
        elif inp == '2':
            play_beep()
        elif inp == '3':
            watch_pid()
        elif inp in ('4', 'd'):
            pid_checker.contents()
        elif inp.startswith('add:'):
            pid_checker.add(inp[inp.find(':')+1:])
        elif inp.startswith('remove:'):
            pid_checker.remove(inp[inp.find(':')+1:])
        else:
            print('Wat?')
Beispiel #12
0
def subcommand(li):
    def is_link(k):
        return Hit(tag=None, key=k).is_link()

    for index, k in enumerate(li, start=1):
        if is_link(k):
            pre = cindex('[{0}]'.format(index), color=cfg.colors[cfg.g.BACKGROUND]["cindex_link"])
        else:
            pre = cindex('[{0}]'.format(index))
        print("{pre} {main_tag} ({doc})".format(
            pre=pre,
            main_tag=hdict[k]["tags"][0],
            doc=hdict[k]["doc"]
        ))
    print("[q] <<")
    while True:
        try:
            inp = raw_input("~~> ").strip()
        except (KeyboardInterrupt, EOFError):
            print()
            return None
        if len(inp) == 0:
            continue
        if inp == 'q':
            return None
        if inp == 'qq':
            my_exit(0)
        try:
            index = int(inp) - 1
            if index < 0:
                raise IndexError
            perform_action(li[index])
            return
        except IndexError:
            print("out of range...")
        except ValueError:
            print('Wat?')
Beispiel #13
0
def show_urls(key):
    o = hdict[key]
    #
    action = o["action"]
    verb = action[0]
    if verb == 'cat':
        fname = "data/" + action[1]
    else:
        return

    # OK, we have the fname
    li = extract_urls(fname)
    for index, url in enumerate(li, start=1):
        print("[{i}] {url}".format(i=index, url=url))
    print("[q] <<")
    while True:
        try:
            inp = raw_input("~~> ").strip()
        except (KeyboardInterrupt, EOFError):
            print()
            return None
        if len(inp) == 0:
            continue
        if inp == 'q':
            return None
        if inp == 'qq':
            my_exit(0)
        try:
            index = int(inp) - 1
            if index < 0:
                raise IndexError
            open_url(li[index])
            return
        except IndexError:
            print("out of range...")
        except ValueError:
            print('Wat?')
Beispiel #14
0
def menu():
    Thread(target=cache_pygmentize).start()
    #
    while True:
        try:
            inp = raw_input(bold('pc> ')).strip()
        except (KeyboardInterrupt, EOFError):
            print()
            my_exit(0)
        if len(inp) == 0:
            continue
        if inp in ('h', 'help()'):
            info()
        elif inp in ('q', 'qq', ':q', ':x', 'quit()', 'exit()'):
            my_exit(0)
        elif inp in ('c', 'clear()'):
            os.system('clear')
            header()
        elif inp in ('light()', 'dark()'):
            if inp == 'light()':
                cfg.g.BACKGROUND = cfg.LIGHT
            else:
                cfg.g.BACKGROUND = cfg.DARK
        elif inp in ('t', 'tags()', 'all()', 'd'):
            SearchHits.show_tag_list(tag2keys.keys())
        elif inp == 'p':
            os.system("python")
        elif inp == 'p3':
            os.system("python3")
        elif inp == 'bpy':
            os.system("bpython")
        elif inp == 'last()':
            print(last_key)
        elif inp == '!!':
            if last_key:
                perform_action(last_key)
        elif inp.startswith('!'):
            cmd = inp[1:]
            os.system(cmd)
        elif inp == 'edit()':
            if last_key:
                edit(last_key)
        elif inp == 'gedit()':
            if last_key:
                gedit(last_key)
        elif inp == 'less()':
            if last_key:
                less(last_key)
        elif inp in ('urls()', 'links()'):
            if last_key:
                show_urls(last_key)
        elif inp in ('cb()', 'tocb()'):
            if last_key:
                to_clipboards(last_key)
        elif inp == 'path()':
            if last_key:
                path_to_clipboards(last_key)
        elif inp == "doc()":
            if last_key:
                show_doc(last_key)
        elif inp == 'json.reload()':
            read_json()
        elif inp in ('json.view()', 'json.edit()'):
            if last_key:
                view_edit_json(last_key)
                read_json()
        elif inp in ("json.edit(this)", "jet()"):
            if last_key:
                edit_entry(last_key)
        elif inp == 'reddit()':
            reddit.reddit()
        elif inp == 'radio()':
            radio.radio_player()
        elif inp == 'conferences()':
            conferences.conferences()
        elif inp == 'mute()':
            radio.radio(None, stop=True)
        elif inp == 'myip()':
            my_ip.show_my_ip()
        elif inp in ('v', 'version()'):
            version()
        elif inp == 'commands()':
            show_commands()
        elif inp == 'add()':
            add_item()
            read_json()
        elif inp == 'hits()':
            SearchHits.show_tag_list()
        elif inp.startswith("pymotw:"):
            site = "pymotw.com"
            cmd_go1(inp[inp.find(':')+1:], site=site)
        elif inp.startswith("go:"):
            cmd_google(inp[inp.find(':')+1:])
        elif inp.startswith("go1:"):
            cmd_go1(inp[inp.find(':')+1:])
        elif inp.startswith("imdb:"):
            site = "imdb.com"
            cmd_go1(inp[inp.find(':')+1:], site=site)
        elif inp.startswith("amazon:"):
            site = "amazon.com"
            cmd_go1(inp[inp.find(':')+1:], site=site)
        elif inp.startswith("youtube:"):
            cmd_youtube(inp[inp.find(':')+1:])
        elif inp.startswith("wp:"):
            site = "wikipedia.org"
            cmd_go1(inp[inp.find(':')+1:], site=site)
        elif inp.startswith("lib:"):
            site = "docs.python.org/2/library/"
            cmd_go1(inp[inp.find(':')+1:], site=site)
        elif inp.startswith("lib3:"):
            site = "docs.python.org/3/library/"
            cmd_go1(inp[inp.find(':')+1:], site=site)
        elif inp.startswith("shorten:"):
            urlshortener.shorten_url(inp[inp.find(':')+1:])
        elif inp.startswith("def:"):
            cmd_def(inp[inp.find(':')+1:])
        elif inp.startswith("pep:"):
            open_pep(inp[inp.find(':')+1:])
        elif inp == 'pep()':
            open_pep(None)
        # disabled, always show the search hits
        #elif inp in tag2keys:
        #    tag = inp
        #    command(tag)
        elif re.search(r'^\d+$', inp):
            try:
                index = int(inp) - 1
                if index < 0:
                    raise IndexError
                tag = SearchHits.hits[index].tag
                command(tag)
            except IndexError:
                print("out of range...")
        elif re.search(r'^\d+\.(doc|action|tags|json|url|link|key|jet|edit)(\(\))?$', inp):
            try:
                pos = inp.find('.')
                index = int(inp[:pos]) - 1
                what = inp[pos+1:].rstrip("()")
                if index < 0:
                    raise IndexError
                hit = SearchHits.hits[index]
                hit.inspect(what)
            except IndexError:
                print("out of range...")
        elif re.search(r'^this.(doc|action|tags|json|url|link|key|jet|edit)(\(\))?$', inp):
            try:
                if not last_key:
                    raise NoLastKeyError
                pos = inp.find('.')
                what = inp[pos+1:].rstrip("()")
                hit = Hit(tag=None, key=last_key)
                hit.inspect(what)
            except NoLastKeyError:
                pass
        elif inp == 'pid()':
            pidcheck.pid_alert()
        elif inp == 'debug()':
            debug()
        elif inp in ('slay()', 'song()'):
            print("Playing:", radio.get_song()['current'])
        else:
            if len(inp) == 1:
                print("too short...")
            else:
                inp = inp.lower()
                SearchHits.show_hint(inp)
Beispiel #15
0
def menu():
    print("[{0:.3f}s]".format(time.time() - start_time), end='\n')
    #
    while True:
        try:
            #inp = raw_input(bold('pc> ')).strip()
            inp = raw_input(bold('{prompt}> '.format(prompt=os.getcwd()))).strip()
        except (KeyboardInterrupt, EOFError):
            print()
            my_exit(0)
        if len(inp) == 0:
            continue
        if inp in ('h', 'help()'):
            info()
        elif inp in ('q', 'qq', ':q', ':x', 'quit()', 'exit()'):
            my_exit(0)
        elif inp in ('c', 'clear()'):
            os.system('clear')
            print_header()
        elif inp in ('light()', 'dark()'):
            if inp == 'light()':
                cfg.g.BACKGROUND = cfg.LIGHT
            else:
                cfg.g.BACKGROUND = cfg.DARK
        elif inp in ('t', 'tags()', 'all()', 'd'):
            SearchHits.show_tag_list(tag2keys.keys())
        elif inp == 'p':
            os.system("python")
        elif inp == 'p3':
            os.system("python3")
        elif inp == 'bpy':
            os.system("bpython")
        elif inp == 'last()':
            print(last_key)
        elif inp == '!!':
            if last_key:
                perform_action(last_key)
        elif inp.startswith('!'):
            cmd = inp[1:]
            os.system(cmd)
        elif inp == 'edit()':
            if last_key:
                edit(last_key)
        elif inp == 'gedit()':
            if last_key:
                gedit(last_key)
        elif inp == 'less()':
            if last_key:
                less(last_key)
        elif inp in ('urls()', 'links()'):
            if last_key:
                show_urls(last_key)
        elif inp in ('cb()', 'tocb()'):
            if last_key:
                to_clipboards(last_key)
        elif inp == 'path()':
            if last_key:
                path_to_clipboards(last_key)
        elif inp == "doc()":
            if last_key:
                show_doc(last_key)
        elif inp == 'json.reload()':
            read_json()
        elif inp in ('json.view()', 'json.edit()'):
            if last_key:
                view_edit_json(last_key)
                read_json()
        elif inp in ("json.edit(this)", "jet()"):
            if last_key:
                edit_entry(last_key)
        elif inp == 'reddit()':
            reddit.reddit()
        elif inp == 'conferences()':
            conferences.conferences()
        elif inp == 'mute()':
            apps.radio.radio(None, stop=True)
        elif inp == 'myip()':
            my_ip.show_my_ip()
        elif inp in ('v', 'version()'):
            version()
        elif inp == 'commands()':
            show_commands()
        elif inp == 'add()':
            add_item()
            read_json()
        elif inp == 'hits()':
            SearchHits.show_tag_list()
        elif inp.startswith("pymotw:"):
            site = "pymotw.com"
            cmd_go1(inp[inp.find(':')+1:], site=site)
        elif inp.startswith("go:"):
            cmd_google(inp[inp.find(':')+1:])
        elif inp.startswith("go1:"):
            cmd_go1(inp[inp.find(':')+1:])
        elif inp.startswith("imdb:"):
            site = "imdb.com"
            cmd_go1(inp[inp.find(':')+1:], site=site)
        elif inp.startswith("amazon:"):
            site = "amazon.com"
            cmd_go1(inp[inp.find(':')+1:], site=site)
        elif inp.startswith("youtube:"):
            cmd_youtube(inp[inp.find(':')+1:])
        elif inp.startswith("wp:"):
            site = "wikipedia.org"
            cmd_go1(inp[inp.find(':')+1:], site=site)
        elif inp.startswith("lib:") or inp.startswith("lib2:"):
            site = "docs.python.org/2/library/"
            cmd_go1(inp[inp.find(':')+1:], site=site)
        elif inp.startswith("lib3:"):
            site = "docs.python.org/3/library/"
            cmd_go1(inp[inp.find(':')+1:], site=site)
        elif inp.startswith("golib:"):
            site = "http://golang.org/pkg/"
            lib = inp[inp.find(':')+1:]
            open_url(urljoin(site, lib))
        elif inp.startswith("shorten:"):
            urlshortener.shorten_url(inp[inp.find(':')+1:])
        elif inp.startswith("def:"):
            cmd_def(inp[inp.find(':')+1:])
        elif inp.startswith("pep:"):
            open_pep(inp[inp.find(':')+1:])
        elif inp == 'pep()':
            open_pep(None)
        elif inp == 'show()':
            show.show()
        elif inp == 'numbers()':
            toggle_line_numbers()
        elif re.search(r"^l([\d,-]+)\.(sh|py|py2|py3|cb|cb\(>\))$", inp):
            fname = key_to_file(last_key)
            selected_lines.process_selected_lines(inp, fname)
        elif inp == 'cd' or inp.startswith('cd '):
            change_dir(inp)
        elif inp == 'pwd()':
            print(os.getcwd())
        elif inp == 'userpass()':
            username_password()
        elif inp == 'apps()':
            apps.menu.main()
        elif inp == 'k':
            os.system("konsole 2>/dev/null &")
        elif inp.startswith("filter:"):
            term = inp[inp.find(':')+1:]
            if last_key:
                perform_action(last_key, term)
        elif inp.startswith("app:"):
            val = inp[inp.find(':')+1:]
            if not val:
                apps.menu.main()
            else:
                apps.menu.start_app(val)
        # shortcuts
        elif inp == 'radio()':
            apps.menu.start_app_by_shortcut('radio')
        # disabled, always show the search hits
        #elif inp in tag2keys:
        #    tag = inp
        #    command(tag)
        elif re.search(r'^\d+$', inp):
            try:
                index = int(inp) - 1
                if index < 0:
                    raise IndexError
                tag = SearchHits.hits[index].tag
                command(tag)
            except IndexError:
                print("out of range...")
        elif re.search(r'^\d+\.(doc|action|tags|json|url|link|key|jet|edit)(\(\))?$', inp):
            try:
                pos = inp.find('.')
                index = int(inp[:pos]) - 1
                what = inp[pos+1:].rstrip("()")
                if index < 0:
                    raise IndexError
                hit = SearchHits.hits[index]
                hit.inspect(what)
            except IndexError:
                print("out of range...")
        elif re.search(r'^this.(doc|action|tags|json|url|link|key|jet|edit)(\(\))?$', inp):
            try:
                if not last_key:
                    raise NoLastKeyError
                pos = inp.find('.')
                what = inp[pos+1:].rstrip("()")
                hit = Hit(tag=None, key=last_key)
                hit.inspect(what)
            except NoLastKeyError:
                pass
        elif inp == 'pid()':
            pidcheck.pid_alert()
        elif inp == 'debug()':
            debug(None)
        elif inp == 'song()':
            print("Playing:", apps.radio.get_song())
        else:
            if len(inp) == 1:
                print("too short...")
            else:
                inp = inp.lower()
                SearchHits.show_hint(inp)