示例#1
0
def input_with_cancellable(cancellable):
    if platform.system() == 'Windows':
        result = ""
        done = False

        while not done:
            while msvcrt.kbhit():
                c = msvcrt.getwche()
                if c in ("\x00", "\xe0"):
                    msvcrt.getwche()
                    continue

                result += c

                if c == "\n":
                    done = True
                    break

            cancellable.raise_if_cancelled()
            time.sleep(0.05)

        return result
    else:
        with cancellable.get_pollfd() as cancellable_fd:
            try:
                rlist, _, _ = select.select([sys.stdin, cancellable_fd], [],
                                            [])
            except (OSError, select.error) as e:
                if e.args[0] != errno.EINTR:
                    raise e

        cancellable.raise_if_cancelled()

        return sys.stdin.readline()
def check_if_all_named(path):
    again = "t"
    print()
    while again == "t":
        count = pdfs_to_name = 0
        left_to_name = []
        for subdir, dirs, _ in os.walk(path):
            dirs.sort(key=natsort_keygen())
            if regex.match(r"^.+04070...\.....", subdir):
                get_steps = regex.match(r"^.+04070...\.....", subdir)[0]
            else:
                continue
            if regex.search(r"04070...\.....$", get_steps):
                steps_inside_path = len(get_steps.split("\\")) + 1
            if len(subdir.split("\\")) == steps_inside_path:
                up_to_merge = os.path.join(
                    subdir, os.path.basename(subdir), "merge"
                )
                is_there_basename = os.path.join(
                    subdir, os.path.basename(subdir)
                )
                if os.path.exists(up_to_merge):
                    if not any(
                        fname.upper().endswith(".PDF")
                        for fname in os.listdir(up_to_merge)
                    ):
                        if not any(
                            fname.upper().endswith(".PDF")
                            for fname in os.listdir(is_there_basename)
                        ):
                            pdfs_to_name, count, left_to_name = add_to_counter(
                                count, pdfs_to_name, subdir, left_to_name
                            )
                elif os.path.exists(is_there_basename):
                    if not any(
                        fname.upper().endswith(".PDF")
                        for fname in os.listdir(is_there_basename)
                    ):
                        pdfs_to_name, count, left_to_name = add_to_counter(
                            count, pdfs_to_name, subdir, left_to_name
                        )
                else:
                    pdfs_to_name, count, left_to_name = add_to_counter(
                        count, pdfs_to_name, subdir, left_to_name
                    )

        print(f"Pozostało {count} operatów, {pdfs_to_name} pdfów do nazwania.")
        if count or pdfs_to_name != 0:
            print("Pokazać listę folderów? t/n\n> ", end="")
            show_folders = msvcrt.getwche().lower()
            print()
            if show_folders == "t":
                for name in natsorted(left_to_name):
                    print(name)
        print("\nPowtórzyć? t/n\n> ", end="")
        again = msvcrt.getwche().lower()
        print()
示例#3
0
def getWFSlot(productUrl):
    headers = {
        'User-Agent':
        'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
    }

    driver = webdriver.Chrome()
    driver.get(productUrl)
    no_open_slots = True
    duration = 5
    time.sleep(180)

    while True:
        if msvcrt.kbhit():
            if 'p' in msvcrt.getwche():
                sys.stdout.write('\rPaused at {}. Press c to continue.'.format(
                    time.strftime('%H:%M:%S', time.localtime())))
                sys.stdout.flush()
                no_open_slots = False
            if 'c' in msvcrt.getwche():
                no_open_slots = True
        if no_open_slots:
            driver.refresh()
            html = driver.page_source
            soup = bs4.BeautifulSoup(html, 'html.parser')

            try:
                for day_button in soup.find_all(
                        'div',
                        class_='ufss-date-select-toggle-text-container'):
                    for availability in day_button.find_all(
                            'div',
                            class_='ufss-date-select-toggle-text-availability'
                    ):
                        for status in availability.stripped_strings:
                            if status != 'Not available':
                                print('SLOTS OPEN!')
                                winsound.Beep(440, 5000)
                                no_open_slots = False
                if no_open_slots:
                    sys.stdout.write(
                        '\rRefreshed at {}. Press p to pause.'.format(
                            time.strftime('%H:%M:%S', time.localtime())))
                    sys.stdout.flush()
                    time.sleep(duration)
            except AttributeError as error:
                print('error: {0}'.format(error))
                continue
        else:
            time.sleep(duration)
def readInput(caption, default, timeout: int = 5):
    start_time = time.time()
    print('{}({})\r\n>'.format(caption, default), end="")
    input = ''
    while True:
        if msvcrt.kbhit():
            chr = msvcrt.getwche()
            if ord(chr) == 13:  # enter_key
                break
            elif ord(chr) == 27:
                break
            elif ord(chr) == 8:
                if input != "":
                    input = input[:-1]
                    msvcrt.putch(b" ")
                    msvcrt.putch(b" ")
                    msvcrt.putch(b"\b")
                    msvcrt.putch(b"\b")
                if len(input) == 0:
                    start_time = time.time()
            elif 32 > ord(chr) or 255 > ord(chr) > 126:  # space_char
                continue
            else:
                input += chr
        if len(input) == 0 and (time.time() - start_time) > timeout:
            break

    if len(input) > 0:
        print()
        return input
    else:
        print("使用默认值")
        return default
def check_for_map_or_sketch(path):
    possible_maps = ["'-M-PROJ-'", "'-M-WPROJ-'", "'-M-UZ-'", "'-M-WYN-'"]
    sketch_coords = ["'-SZK-POL-'", "'-W-WSP-'"]
    again = "t"
    print()
    while again == "t":
        print_results = []
        for subdir, dirs, _ in os.walk(path):
            dirs.sort(key=natsort_keygen())
            if any(
                regex.search(r"-.+-", fname) for fname in os.listdir(subdir)
            ):
                operat = os.path.basename(subdir)
                if "merge" in subdir:
                    operat = os.path.basename(os.path.dirname(subdir))
                for item in sketch_coords:
                    if not any(
                        item.strip("'") in fname.upper()
                        for fname in os.listdir(subdir)
                    ):
                        print_results.append(f"{operat} nie zawiera {item}.")
                if not any(
                    possibility.strip("'") in fname
                    for possibility in possible_maps
                    for fname in os.listdir(subdir)
                ):
                    missing_map = ", ".join(maps for maps in possible_maps)
                    print_results.append(
                        f"{operat} nie zawiera żadnej z map: {missing_map}."
                    )
        for result in sorted(set(print_results)):
            print(result)
        print("Powtórzyć? t/n\n> ", end="")
        again = msvcrt.getwche().lower()
        print("\n")
示例#6
0
def input_with_timeout(prompt, timeout, gameset, timer=time.monotonic):
    sys.stdout.write(prompt)
    sys.stdout.flush()
    endtime = timer() + timeout
    result = []
    countdowner=endtime-timer()
    print(math.ceil(countdowner), end=' ')
    while timer() < endtime:
        
        #To check if key for input has been pressed yet, gamesetting taken into account
        
        if msvcrt.kbhit():
            print("")
            result.append(msvcrt.getwche())
            if gameset==1:
                if result[-1] =='\r':
                    return int(''.join(result[:-1]))
            elif gameset==2:
                return int(''.join(result[:]))
        else:
            if countdowner-(endtime-timer())>=1:
                countdowner=endtime-timer()
                sys.stdout.flush()
                print(math.ceil(endtime-timer()), end=' ')
        time.sleep(0.04)
    raise TimeoutExpired
def main():
    # path = r"D:\WPG\inowroclawski\040701_1.0006"
    path = input("\nWklej ścieżkę:\n> ")
    end_script = ""
    while end_script != "0":
        print("\nWybierz jedną z opcji:")
        print(
            """
    (1)  Liczenie nazwanych plików
    (2)  Sprawdzanie czy wszystko zostało nazwane lub ile pozostało do nazwania
    (3)  Sprawdź czy w każdym operacie jest mapa, szkic i wykaz
    (4)  Zagnieżdżone katalogi
    (5)  Popraw numerację dokumentów i stron
    (6)  Czy w merge są wszytkie nazwy plików
    (0)  Wyjście z programu
    """
        )
        end_script = msvcrt.getwche()
        print()
        if end_script == "1":
            count_if_file_named(path)
        elif end_script == "2":
            check_if_all_named(path)
        elif end_script == "3":
            check_for_map_or_sketch(path)
        elif end_script == "4":
            move_up_nested_merge(path)
        elif end_script == "5":
            fix_numbers(path)
        elif end_script == "6":
            no_missing_names(path)
    input("\nWciśnij ENTER lub zamknij okno ręcznie...\n> ")
示例#8
0
    def run(self):
        '''
        Loop over parameters creates a list of experiments parsed from the repeats (lists) in the experiment description file.
        It is grouped by ID. The idea behind this is that we will initialize only once the first time for a given ID. This allows
        us to scan over parameters without having to recompile sequences/ setup counting cards/ plots again. If you need to reinitialize
        a sequence - 
        
        1) Use a different ID. To avoid rewriting parameters in the experiment description file, parameters that 
        constant over multiple IDs can be write the IDs as a tuple. 
        
        2) To scan over a parameter in s sequence, use the parameter key 'Sequences_scan' and this should initialize the sequences again
        '''

        parameter_loop = self.loop_over_parameters(self.parameters)
        for parameters_ID in parameter_loop:
            ID = parameters_ID[0]
            num_parameters = len(parameters_ID[1])
            for ix in xrange(num_parameters):
                if ix == 0 and ix == num_parameters - 1:
                    self.run_expt(ID, parameters_ID[1][ix], 1, 1)
                elif ix == 0:
                    self.run_expt(ID, parameters_ID[1][ix], 1, 0)
                elif ix == num_parameters - 1:
                    self.run_expt(ID, parameters_ID[1][ix], 0, 1)
                else:
                    self.run_expt(ID, parameters_ID[1][ix], 0, 0)

                if msvcrt.kbhit():
                    if msvcrt.getwche() == '\r':
                        break
示例#9
0
def input_with_timeout(timeout=2):
    if OS_NAME == 'posix':  # *nix
        import select
        import sys

        ready, _, _ = select.select([sys.stdin], [], [], timeout)
        if ready:
            try:
                return sys.stdin.readline().rstrip('\n')
            except OSError:
                return None
        raise TimeoutExpired

    else:  # windows
        import msvcrt

        endtime = monotonic() + timeout
        result = []
        while monotonic() < endtime:
            if msvcrt.kbhit():
                result.append(msvcrt.getwche())
                if result[-1] == '\n' or result[-1] == '\r':
                    return ''.join(result[:-1])
            sleep(0.05)  # 这个值太大会导致丢失按键信息
        raise TimeoutExpired
示例#10
0
def shell():
    line = ''  #we build up the line with input char by char
    global m3u
    tabtries = 0  #this will keep track of the attempts to tab complete
    tabcompleted = ''
    prompt()
    while(1):
        bit = str(msvcrt.getwche()) #<=========INPUT using Vc++ runtime
        #asciichar = chr(ord(bit)) #useful when using getch()
        
        if(bit == '\r'):
            if(tabtries > 0):
                execute(tabcompleted)
            else:
                execute(line)
            line = ''
            tabtries = 0
            tabcompleted = ''
            prompt()
        elif(bit == '\t'):
            tabcompleted = tabcomplete(line, tabtries)
            tabtries += 1
            clrline()
            prompt()
            printf(tabcompleted)
        elif(bit == '\b'): #TODO: remove the last visible char and the last recorded char
            clrline()
            line = ''
            prompt()
            tabtries = 0
            tabcompleted = ''

        elif(not bit == '\xff'):
            line += bit #build up the command to be interpreted
            tabcompleted += bit
示例#11
0
    def Pull(self):
        os.system('python process.py')
        t0 = time.time()
        print("Press Enter for hard pull")

        while True:
            t1 = time.time()
            t = t1 - t0
            self.xs.append(t)
            self.ys.append(self.pmd.power.magnitude * 1000)
            while len(self.xs) != len(self.ys):
                del self.xs[-1]

            values = {
                'x': self.xs,
                'y': self.ys,
            }

            if msvcrt.kbhit():
                if msvcrt.getwche() == '\r':
                    np.savetxt("power.csv", self.ys, delimiter=",")
                    self.gpd.set_voltage(12)
                    self.gpd.set_output(1)
                    self.gpd.set_output(0)
                    break

            self.Pull.acquire(values)
            time.sleep(0.05)
        return
示例#12
0
文件: ui.py 项目: 47-/Cyprium
 def _getch_win(cl, echo=False):
     import msvcrt
     import time
     while not msvcrt.kbhit():
         time.sleep(0.1)
     if echo:
         return msvcrt.getwche()
     return msvcrt.getwch()
示例#13
0
 def _getch_win(cl, echo=False):
     import msvcrt
     import time
     while not msvcrt.kbhit():
         time.sleep(0.1)
     if echo:
         return msvcrt.getwche()
     return msvcrt.getwch()
def input_with_timeout(a,b,timer):
    end = time.time() + timer
    print('%.2f - %.2f =' %(a, b))
    result = []
    while time.time() < end:
        if msvcrt.kbhit():
            result.append(msvcrt.getwche())
            if result[-1] == "\r":
                return "".join(result[:-1])
    raise TimeoutExpired
示例#15
0
def input_with_timeout(timeout, timer=time.monotonic):
    endtime = timer() + timeout
    result = []
    while timer() < endtime:
        if msvcrt.kbhit():
            result.append(msvcrt.getwche())
            if result[-1] == '\r':
                return ''.join(result[:-1])
        time.sleep(0.04)
    raise timeoutExpired
示例#16
0
def input_with_timeout(prompt, timeout, timer=time.monotonic):
    sys.stdout.write(prompt)
    sys.stdout.flush()
    endtime = timer() + timeout
    result = []
    while timer() < endtime:
        if msvcrt.kbhit():
            result.append(msvcrt.getwche()) #XXX can it block on multibyte characters?
            if result[-1] == '\r':   #XXX check what Windows returns here
                return ''.join(result[:-1])
        time.sleep(0.04) # just to yield to other processes/threads
    raise TimeoutExpired
示例#17
0
def get_input(prompt, timeout, timer=time.monotonic):
    sys.stdout.write(prompt)
    sys.stdout.flush()
    endtime = timer() + timeout
    result = []
    while timer() < endtime:
        if msvcrt.kbhit():  # msvcrt.kbhit() returns True if a keypress is waiting to be read.
            result.append(msvcrt.getwche())  # We read a keyspress. More details can be found at https://docs.python.org/3/library/msvcrt.html#msvcrt.getche
            if result[-1] == '\r':
                return ''.join(result[:-1])
        time.sleep(0.04) # give other processes/threads to read the keystroke, if needed
    raise TimeoutExpired
示例#18
0
def get_input(r_type: type, hint: str) -> type:
    display(hint)
    ret = StringIO()
    while True:
        if msvcrt.kbhit:
            key = msvcrt.getwche()
            if str(key) != "\r":
                ret.write(key)
            else:
                display("\n")
                ret.seek(0)
                return r_type(ret.read())
示例#19
0
def mainLoop():
    i= time.time()
    checkRate = 10
    tree = CurrencyXMLTree(getXMLFromURL("http://rates.fxcm.com/RatesXML"))
    tester = CurrencyTester(tree, 'EURUSD', 1.38355, 1)
    print "Currently looking at currency "+tester.currency+" when it reaches target rate "+str(tester.targetValue)+" checking every "+str(checkRate)+" seconds."
    print "Press ENTER at any time to bring up the options menu."

    while True:
        if (time.time() - i > checkRate):
                tree = CurrencyXMLTree(getXMLFromURL("http://rates.fxcm.com/RatesXML"))
                #print tester.currency+" at: "+str(tree.getCurrentRate(tester.currency))
                if (tester.compareValues(tree)):
                    if(tester.startingLine == 1):
                        print tester.currency+" has gone above target rate "+str(tester.targetValue)+", current rate at "+str(tree.getCurrentRate(tester.currency))+"!"
                    elif(tester.startingLine == -1):
                        print tester.currency+" has gone below target rate "+str(tester.targetValue)+", current rate at "+str(tree.getCurrentRate(tester.currency))+"!"
                #print ("tester1 evaluates to: ",tester.compareValues(tree))
                i = time.time()
                
                                       
        if msvcrt.kbhit():
            if msvcrt.getwche() == '\r':
                print "What would you like to do?"
                print """
[1] Change my currency configuration.
[2] Exit the program.
                    """
                selection = getChoiceNumber(2)
                if(selection == 1):
                    step1 = False
                    while(not step1):
                        currencyName = getString("Please enter which currency you want to track: ")
                        if(not tree.checkIfSymbolExists(currencyName)):
                            print "This currency name was not found, please enter a valid currency name."
                        else:
                            step1 = True
                    
                    targetRate = getFloat("Please enter the target rate: ")
                    "get new target rate"
                    print "Would you like to be notified when the target rate is above [1] or below [2] the previously entered value?"
                    choiceAboveOrBelow = getChoiceNumber(2)
                    if(choiceAboveOrBelow == 1):
                        tester = CurrencyTester(tree,currencyName,targetRate,1)
                    else:
                        tester = CurrencyTester(tree,currencyName,targetRate,-1)

                    print "Currently looking at currency "+tester.currency+" when it reaches target rate "+str(tester.targetValue)+" checking every "+str(checkRate)+" seconds."
                elif(selection == 2):
                    break
        time.sleep(0.1)
    print i
示例#20
0
    def read(self):
        flag = True
        while True == flag:
            char = msvcrt.getwche()
            if u'\r' == char:
                self.stream.write('\n')
                char = u'\0'
                flag = False
            self.bytearray.extend(char.encode(self.set))

        string = "{}".format(self.bytearray.decode(self.set))
        self.bytearray.clear()
        return string
def changes(change_type, numbers_to_change):
    print(
        f"Chcesz zobaczyć zmiany w numerach {change_type}, zanim je zrobię? \
t/n\n> ",
        end="",
    )
    print_changes = msvcrt.getwche().lower()
    print()
    if print_changes == "t":
        for change in natsorted(numbers_to_change):
            names = change.split("\t")[1]
            old_name, new_name = names.split("_--_")
            print(f"{old_name}{new_name}")
    print("\nDokonać zmian? t/n\n> ", end="")
    make_changes = msvcrt.getwche().lower()
    print()
    if make_changes == "t":
        delete_double_underscore = []
        for change in natsorted(numbers_to_change):
            # with open(
            #     r"V:\P32_kopie_prac\Cyfryzacja_powiat inowroclawski\_MACIEK\20200527_040707_5_ewidencyjne-zmiany_w_nazwach\python.txt",
            #     "a",
            #     encoding="utf-8",
            # ) as pyt_dok:
            #     pyt_dok.write(f"{change}\n")
            file_path = change.split("\t")[0]
            old_name, new_name = change.split("\t")[1].split(" --> ")
            os.rename(
                os.path.join(file_path, old_name),
                os.path.join(file_path, new_name),
            )
            delete_double_underscore.append(os.path.join(file_path, new_name))
        for underscore in delete_double_underscore:
            os.rename(
                underscore,
                underscore.split("_--_")[0] + underscore.split("_--_")[1],
            )
    return make_changes
示例#22
0
def beolv():
    """Adatok beolvasása"""
    for i in range(3):
        print("-"*25, end="\n")
        for j in range(3):
            for k in range(3):
                print("| ", end="", flush=True)
                for l in range(3):
                    ch = getwche()
                    if ch=="x":
                        tesztbemenet()
                        return
                    while not (ch.isdigit() or ch == " "):
                        print("\b \b", end="", flush=True)
                        ch = getwche()
                    if ch=="0" or ch==" ":
                        t[3*i+j][3*k+l] = {}
                        print("\b_ ", end="", flush=True)
                    else:
                        t[3*i+j][3*k+l] = {int(ch)}
                        print(" ", end="", flush=True)
            print("|", end="\n")
    print("-"*25)
示例#23
0
 def input_with_timeout(prompt, timeout, timer=time.monotonic):
     sys.stdout.write(prompt)
     sys.stdout.flush()
     endtime = timer() + timeout
     result = []
     while timer() < endtime:
         if msvcrt.kbhit():
             result.append(msvcrt.getwche()
                           )  #XXX can it block on multibyte characters?
             if len(result) >= 1:  #XXX check what Windows returns here
                 return self.doc_replacer()
                 #time.sleep(10)
                 #return self.getNada()
         time.sleep(0.04)  # just to yield to other processes/threads
示例#24
0
def input_with_timeout(prompt: str, timeout: int):
    """
    Requests user input and waits until the timeout expired.
    :param prompt: a string that will be printed on the screen.
    :param timeout: timeout to wait.
    :return: input string or empty line if the timeout expired.
    """
    platform = system()
    res_str = ''
    if platform == 'Windows':
        import msvcrt
        import time

        print_without_end_line(prompt)
        start_time = time.monotonic()
        end_time = start_time + timeout
        sleep_time = 0.05

        while time.monotonic() < end_time:
            if msvcrt.kbhit():
                c = msvcrt.getwche()
                if c in ['\r', '\n']:
                    print()
                    return res_str
                if c == '\003':
                    raise KeyboardInterrupt
                if c == '\b':
                    res_str = res_str[:-1]
                    print_without_end_line(''.join(['\r', ' ' * len(prompt + res_str + ' '), '\r', prompt, res_str]))
                else:
                    res_str += c
            time.sleep(sleep_time)

        print()
        return ''
    else:
        import selectors

        print_without_end_line(prompt)
        with selectors.DefaultSelector() as selector:
            selector.register(sys.stdin, selectors.EVENT_READ)
            events = selector.select(timeout)

            if events:
                key, _ = events[0]
                res_str = key.fileobj.readline().rstrip('\n')
            else:
                print()
            selector.unregister(sys.stdin)
        return res_str
示例#25
0
def old_windows_input(prompt, timeout=60, timer=time.monotonic):
    prompt = f"| {prompt}: "
    sys.stdout.write(prompt)
    sys.stdout.flush()
    endtime = timer() + timeout
    result = []
    while timer() < endtime:
        if msvcrt.kbhit():
            result.append(msvcrt.getwche())
            if result[-1] == "\n":
                out = "".join(result[:-1])
                logger.debug(f"{prompt[2:]}{out}")
                return out
        time.sleep(0.04)
    raise TimeoutExpired
def input_with_timeout(prompt, timeout, timer=time.monotonic):
    '''
    This function gives option to provide an input but on a timer
    '''
    sys.stdout.write(prompt)
    sys.stdout.flush()
    endtime = timer() + timeout
    result = []
    while timer() < endtime:
        if msvcrt.kbhit():
            result.append(
                msvcrt.getwche())  #XXX can it block on multibyte characters?
            if result[-1] == '\r':
                return ''.join(result[:-1])
        time.sleep(0.04)  # just to yield to other processes/threads
    raise TimeoutExpired
示例#27
0
 def get_input(self):
     while msvcrt.kbhit():
         c = msvcrt.getwche()
         if c == '\r':  # new line
             c = '\n'
             self.input += c
             self.protocol.dataReceived(self.input.encode())
             self.input = ''
         elif c in ('\xE0', '\x00'):
             # ignore special characters
             msvcrt.getwch()
         elif c == '\x08':  # delete
             self.input = self.input[:-1]
         else:
             self.input += c
     reactor.callLater(self.interval, self.get_input)
def move_up_nested_merge(path):
    to_be_moved = []
    for subdir, dirs, _ in os.walk(path):
        dirs.sort(key=natsort_keygen())
        current_dir = subdir
        if regex.match(r"^.+040701..\.....", current_dir):
            get_steps = regex.match(r"^.+040701..\.....", current_dir)[0]
        else:
            continue
        if regex.search(r"040701..\.....$", get_steps):
            steps_inside_path = len(get_steps.split("\\")) + 1
        if len(current_dir.split("\\")) == steps_inside_path:
            operat = os.path.basename(current_dir)
            up_to_merge = os.path.join(current_dir, operat, operat, "merge",)
            is_there_basename = os.path.join(current_dir, operat, operat,)
            if os.path.exists(up_to_merge):
                merge = os.path.join(operat, "merge")
                to_be_moved.append(
                    f"{current_dir}--__--{merge}--__--{up_to_merge}"
                )
            if os.path.exists(is_there_basename):
                if len(os.listdir(is_there_basename)) > 1:
                    to_be_moved.append(
                        f"{current_dir}--__--{operat}--__--{is_there_basename}"
                    )
    if to_be_moved:
        end_script = ""
        while end_script != "0":
            print(
                """
Co chcesz zrobić?
    (1)  Podejrzeć listę zagnieżdżonych katalogów
    (2)  Wyciągnąć zagnieżdżone katalogi
    (0)  Wróć do menu głównego
    """
            )
            end_script = msvcrt.getwche()
            print()
            if end_script == "1":
                print_nested_catalogues(to_be_moved)
            elif end_script == "2":
                move_files_up(to_be_moved)
                print(" --- PRZENIESIONE --- ")
                end_script = "0"
    else:
        print(" --- BRAK ZAGNIEŻDŻEŃ --- ")
def input_with_timeout(
    prompt,
    timeout,
    timer=time.monotonic
):  ### from https://stackoverflow.com/questions/15528939/python-3-timed-input
    sys.stdout.write(prompt)
    sys.stdout.flush()
    endtime = timer() + timeout
    result = []
    while timer() < endtime:
        if msvcrt.kbhit():
            result.append(
                msvcrt.getwche())  #XXX can it block on multibyte characters?
            if result[-1] == '\r':
                return ''.join(result[:-1])
        time.sleep(0.04)  # just to yield to other processes/threads
    raise TimeoutExpired
示例#30
0
文件: mtinput.py 项目: myprg/pybase
 def input(self, prompt=PROMPT):
     with self._lock:
         self._buf = []
         self._prompt = prompt
     self._stdout.write(self._prompt + " ")
     self._stdout.flush()
     while True:
         ch = msvcrt.getwche()
         if ch in "\r\n":
             with self._lock:
                 buf = u"".join(self._buf)
                 self._buf = []
             buf = normstr(buf)
             return buf
         else:
             with self._lock:
                 self._buf.append(ch)
示例#31
0
def clean():
    print()
    print("Cleaning Mode On (press enter to end cleaning mode)")
    song = Spotify.playback_currently_playing()
    deletedSongs = []

    if song == None:
        print(
            "Please start by playing a song in the playlist that you want to clean"
        )
        return "Failed Preconditions"

    print("Playing: " + song.item.name)
    #Check users current playing and performs deltions as nessecary until user input in terminal
    while True:
        currentSong = Spotify.playback_currently_playing()
        currentSongDuration = Spotify.playback_currently_playing(
        ).item.duration_ms
        #on song change
        if (currentSong.item.name != song.item.name):
            print("Playing: " + currentSong.item.name)
            if (songProgress < 0.95):
                songID = song.item.uri
                context = Spotify.playback_currently_playing().context
                playlist = context.uri[context.uri.index('playlist') + 9:]
                Spotify.playlist_remove(playlist, [songID])
                print("deleted " + song.item.name)
                deletedSongs.append(song.item.name)
            song = currentSong

        #update progress
        songProgress = Spotify.playback_currently_playing(
        ).progress_ms / currentSongDuration

        #break if user input
        if msvcrt.kbhit():
            if msvcrt.getwche() == '\r':
                break
        time.sleep(1)

    print("Cleaning Mode Off")
    print()
    print("Deleted Songs:")
    for i in deletedSongs:
        print(i)
示例#32
0
def windows_input(prompt, timeout=5):
    sys.stdout.write(f"| {prompt}: ")
    sys.stdout.flush()
    result = []
    start_time = time.time()
    while True:
        if msvcrt.kbhit():
            char = msvcrt.getwche()
            if ord(char) == 13:  # enter_key
                out = "".join(result)
                print("")
                logger.debug(f"{prompt}: {out}")
                return out
            elif ord(char) >= 32:  #space_char
                result.append(char)
        if (time.time() - start_time) > timeout:
            print("")
            raise TimeoutExpired
示例#33
0
文件: Maze.py 项目: x3naa/Krakathon
def move_player(maze):
    valid = False
    while (not valid):
        # inp = input('')[0].lower()
        inp = msvcrt.getwche()
        print(inp)
        if (inp in ['w', 'a', 's', 'd']):
            valid = True
            if inp == 'w':
                move_up(maze)
            elif inp == 'a':
                move_left(maze)
            elif inp == 'd':
                move_right(maze)
            elif inp == 's':
                move_down(maze)
            move_enemy(maze)
        if inp == 'x':
            sys.exit()
示例#34
0
	def save(self):
		print('Press Enter for Save Screen')
		index=0
		while True:
			if msvcrt.kbhit():
				if msvcrt.getwche() == '\r':
					self.osc.datasource(1)
					self.xs,self.ys=self.osc.curv()
					self.osc.datasource(3)
					self.x1s,self.y1s=self.osc.curv()
					values = {
							'x': self.xs,
							 'y': self.ys,
							 'x1': self.x1s,
							 'y1': self.y1s
							}
					self.save.acquire(values)
					self.saveData(self.xs,self.ys,self.x1s,self.y1s,str(index),self.field)
					print('Press Enter for Save Screen')
					index=index+1
示例#35
0
def user_interface():  # requests a move command from the user, then prints all objects current positions
    import os
    import platform
    if platform.system() == 'Windows':
        os.system('cls')  # will clear the screen between turns on Windows
    else:
        os.system('clear')  # will clear the screen between turns on Linux or OSX

    print_map()
    
    PromptText.print_out()
    
    print

    if platform.system() == 'Vindows':
        import msvcrt
        print "Which direction would you like to move in? <N E S W>  (" + str(turn_count) + " turns remaining. Q to quit.) : "
        input_char = msvcrt.getwche()
    else:
        input_char = raw_input("Which direction would you like to move in? <N E S W>  (" + str(turn_count) + " turns remaining. Q to quit.) : ")

    input_char = input_char.upper()  # input will accept upper or lower case valid directions

    print

    if input_char == 'N':
        hero.position = prompt_decision((hero.position[0] - 1, hero.position[1]))
    elif input_char == 'S':
        hero.position = prompt_decision((hero.position[0] + 1, hero.position[1]))
    elif input_char == 'E':
        hero.position = prompt_decision((hero.position[0], hero.position[1] + 1))
    elif input_char == 'W':
        hero.position = prompt_decision((hero.position[0], hero.position[1] - 1))
    elif input_char == 'Q':
        print("You have chosen to end the game. Goodbye.")
        raw_input("Press Enter to close game.")  # intended to give the user a chance to review the screen before exiting
        import sys
        sys.exit()
示例#36
0
文件: TIMER.py 项目: Govind9/Python
    seq=[]
    seq.append(moves[random.randint(0,17)])
    print(seq[0],end=' ')
    for i in range(1,20):
        x=random.randint(0,17)
        while ((seq[i-1]==moves[x]) or (x%3==0 and (seq[i-1]==moves[x+1] or seq[i-1]==moves[x+2])) or ((x-1)%3==0 and (seq[i-1]==moves[x+1] or seq[i-1]==moves[x-1]) ) or ((x-2)%3==0 and (seq[i-1]==moves[x-1] or seq[i-1]==moves[x-2]) )):
            x=random.randint(0,17)
        seq.append(moves[x])
        print(seq[i],end=' ')
z=0
i=1
tm=[]
while True:
    scramble()
    print("\nPress Any Key to start the TIMER\n[Press Q to delete a record]")
    if m.getwche()=='q' :
        try:
            if tm:
                tm.__delitem__(int(input('\nEnter the record index\n')))
                i=i-2
                os.system('cls')
                if i<0:
                    #print('Index Out of range')
                    i=0
            else :
                os.system('cls')
                print('No record to delete')
                i=0
        except :
            os.system('cls')
            #print('Index out of range')
示例#37
0
ASADMIN = 'asadmin'

if sys.argv[-1] != ASADMIN:
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
    shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
    #sys.exit(0)
    port = input("enter port ")
    server = "localhost"
    server_ip = socket.gethostbyname(server)
    monitor_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    monitor_s.bind((server,int(port)))
    monitor_s.listen(1)
    connection = monitor_s.accept()
    while True:
        data = connection.recv(1024)
        connection.sendall(data)
        if msvcrt.kbhit():
            if msvcrt.getwche() == '\r':
                break
    print (sys.getsizeof(data))
    connection.close()

#for i in range(1,1025):
#
#result = monitor_s.connect_ex((server_ip,int(port)))
#if result==0:
 #   print("port open",port,"and ip",server_ip)
#else:
 #   print("error at",port,"",server_ip)