Python fileinput.input() Examples

The following are 30 code examples of fileinput.input(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module fileinput , or try the search function .
Example #1
Source File: modules.py    From gpt with GNU General Public License v3.0 6 votes vote down vote up
def choosemult(self, path):
        """Specify multiplier for timelapse video."""
        os.chdir(path)
        self.makeldir()
        while 1:
            try:
                mult = float(input(_("Multiplier: ")))
                if mult == 0:
                    break
                elif mult <= 1:
                    print(_("Multiplier must be larger than 1."))
                else:
                    self.ffmpeg_vid(path, mult)
                    break
            except ValueError:
                print(_("Invalid input (no number). Try again...")) 
Example #2
Source File: modules.py    From gpt with GNU General Public License v3.0 6 votes vote down vote up
def copydir_prompt(self, default, c):
        """Value returned is name of default or selected subfolder"""
        if c == 0:
            return default
        while 1:
            try:
                prompt = input(_("Choose destination folder (return for default value: {}): ").format(default))
                if prompt == "":
                    return default
                elif int(prompt) > c or int(prompt) < 1:
                    print(_("Invalid input, input must be integer between 1 and {}. Try again...").format(c))
                else:
                    return self.copydirlist[int(prompt)-1][1]
            except ValueError:
                print(_("Invalid input (integer required). Try again..."))

    # Medien kopieren 
Example #3
Source File: modules.py    From gpt with GNU General Public License v3.0 6 votes vote down vote up
def chwdir(self):
        """Setting up working directory, default: ~/GP"""
        while 1:
            befehl = input(_("Change working directory? (y/N) "))
            if befehl == "y":
                newdir = input(_("Input path: "))
                if newdir == "":
                    self.show_message(_("No change."))
                    break
                else:
                    self.chkdir(newdir)
                    self.stdir = os.getcwd()
                    self.replace_wdir_config(newdir)
                    break
            elif befehl == "n" or befehl == "":
                self.show_message(_("Everything stays as it is."))
                break
            else:
                self.show_message(_("Invalid input"))

    # function exclusively called by cli 
Example #4
Source File: modules.py    From gpt with GNU General Public License v3.0 6 votes vote down vote up
def delfiles(self, ftype):
        """Dateien bestimmten Typs löschen"""
        while 1:
            print()
            befehl = input(_("Delete (y/n) "))
            if befehl == "y":
                for file in os.listdir(self.dir):
                    if file.endswith(ftype):
                        self.show_message(_("Deleting {}.").format(file))
                        os.remove(file)
                break
            elif befehl == "n":
                break
            else:
                self.show_message(_("Invalid input. Try again..."))

    # Menü 
Example #5
Source File: modules.py    From gpt with GNU General Public License v3.0 6 votes vote down vote up
def shell(self):
        """Input prompt"""
        while 1:
            print()
            befehl = input()
            if befehl == "h" or befehl == "":
                self.help()
            elif befehl == "r":
                self.sortfiles()
            elif befehl == "c":
                self.handlecard()
            elif befehl == "w":
                self.chwdir()
            elif befehl == "d":
                self.confirm_format()
            elif befehl == "v":
                ctl.countvid()
            elif befehl == "i":
                ctl.countimg()
            elif befehl == "k":
                kds.countvid()
            elif befehl == "q":
                break
            else:
                print(_("Invalid input. Try again...")) 
Example #6
Source File: modules.py    From gpt with GNU General Public License v3.0 6 votes vote down vote up
def on_app_startup(self, app):
        # initiate custom css
        # css stylesheet
        stylesheet = os.path.join(cli.install_dir, "ui", "gtk.css")
        # ...encode() is needed because CssProvider expects byte type input
        with open(stylesheet, "r") as f:
            css = f.read().encode()

        style_provider = Gtk.CssProvider()
        style_provider.load_from_data(css)

        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(),
            style_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        ) 
Example #7
Source File: modules.py    From gpt with GNU General Public License v3.0 6 votes vote down vote up
def choosevid(self, c):
        """Create and open Kdenlive project file for selected folder"""
        while 1:
            try:
                befehl = int(input(_("Select directory to create and open Kdenlive project (0 to cancel): ")))
                if befehl == 0:
                    break
                elif befehl > c or befehl < 0:
                    print(_("Invalid input, input must be integer between 1 and {}. Try again...").format(c))
                else:
                    message = _("Processing Kdenlive project for {}").format(self.wherevid[befehl-1][1])
                    cli.show_message(message)
                    self.create_project(self.wherevid[befehl-1][1])
                    break
            except ValueError:
                print(_("Invalid input (no integer). Try again...")) 
Example #8
Source File: gdelt.py    From psychsim with MIT License 6 votes vote down vote up
def parseCAMEO():
    """
    Extracts mapping and reverse mapping of CAMEO codes to/from event labels
    @rtype: dict,dict
    """
    cameo = {}
    oemac = {}
    for line in fileinput.input(os.path.join(os.path.dirname(__file__),'cameo.txt')):
        elements = line.split(':')
        if len(elements) == 2:
            code = int(elements[0])
            event = elements[1].strip()
            cameo[code] = event
            oemac[event] = code
    return cameo,oemac

# Global variables for reference, CAMEO and GDELT formats 
Example #9
Source File: mysqldump_to_csv.py    From mysqldump-to-csv with MIT License 6 votes vote down vote up
def main():
    """
    Parse arguments and start the program
    """
    # Iterate over all lines in all files
    # listed in sys.argv[1:]
    # or stdin if no args given.
    try:
        for line in fileinput.input():
            # Look for an INSERT statement and parse it.
            if is_insert(line):
                values = get_values(line)
                if values_sanity_check(values):
                    parse_values(values, sys.stdout)
    except KeyboardInterrupt:
        sys.exit(0) 
Example #10
Source File: run_fio.py    From glusto-tests with GNU General Public License v3.0 6 votes vote down vote up
def generate_workload_using_fio(root_dirname, ini_file):
    """Populate data in the given directory using fio tool.

    Args:
        root_dirname (str): Directory name
        ini_file (str): fio job file

    Example:
        generate_workload_using_fio("/tmp", 'job1.ini')

    """
    dirpath_list = [x[0] for x in (os.walk(root_dirname))]

    for dirpath in dirpath_list:
        fname = "[" + dirpath + "/fio_" + os.path.basename(ini_file) + "]"
        for line in fileinput.input(ini_file, inplace=True):
            line = re.sub(r'\[.*\]', fname, line.rstrip())
            print(line)

        fio_cmd = "fio " + ini_file
        subprocess.call(fio_cmd, shell=True) 
Example #11
Source File: ReVerb.py    From Snowball with GNU General Public License v3.0 6 votes vote down vote up
def main():
    # for testing, it extracts PER-ORG relationships from a file, where each line is a sentence with
    # the named-entities tagged
    reverb = Reverb()
    for line in fileinput.input():
        sentence = Sentence(line, "ORG", "ORG", 6, 1, 2, None)
        for r in sentence.relationships:
            pattern_tags = reverb.extract_reverb_patterns_tagged_ptb(r.between)
            # simple passive voice
            # auxiliary verb be + main verb past participle + 'by'
            print(r.ent1, '\t', r.ent2)
            print(r.sentence)
            print(pattern_tags)
            if reverb.detect_passive_voice(pattern_tags):
                print("Passive Voice: True")
            else:
                print("Passive Voice: False")
            print("\n")
    fileinput.close() 
Example #12
Source File: deduplicate_lines.py    From fairseq with MIT License 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--workers', type=int, default=10)
    parser.add_argument('files', nargs='*', help='input files')
    args = parser.parse_args()

    seen = set()
    with fileinput.input(args.files, mode='rb') as h:
        pool = Pool(args.workers)
        results = pool.imap_unordered(get_hashes_and_lines, h, 1000)
        for i, (hash, raw_line) in enumerate(results):
            if hash not in seen:
                seen.add(hash)
                sys.stdout.buffer.write(raw_line)
            if i % 1000000 == 0:
                print(i, file=sys.stderr, end="", flush=True)
            elif i % 100000 == 0:
                print(".", file=sys.stderr, end="", flush=True)
    print(file=sys.stderr, flush=True) 
Example #13
Source File: __init__.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def _create_combined_bundle_file(self):
        leap_ca_bundle = ca_bundle.where()

        if self._ca_cert_path == leap_ca_bundle:
            return self._ca_cert_path  # don't merge file with itself
        elif not self._ca_cert_path:
            return leap_ca_bundle

        tmp_file = tempfile.NamedTemporaryFile(delete=False)

        with open(tmp_file.name, 'w') as fout:
            fin = fileinput.input(files=(leap_ca_bundle, self._ca_cert_path))
            for line in fin:
                fout.write(line)
            fin.close()

        return tmp_file.name 
Example #14
Source File: modules.py    From gpt with GNU General Public License v3.0 6 votes vote down vote up
def chooseimg(self, c):
        """Create timelapse video(s) for all image files in selected directory"""
        while 1:
            try:
                befehl = int(input(_("Select directory to create timelapse video of (0 to cancel): ")))
                if befehl == 0:
                    break
                elif befehl > c or befehl < 0:
                    print(_("Invalid input, input must be integer between 1 and {}. Try again...").format(c))
                else:
                    print(_("Create timelapse for directory {}").format(self.whereimg[befehl-1][1]))
                    self.ldir_img(self.whereimg[befehl-1][1])
                    self.ffmpeg_img(self.whereimg[befehl-1][1])
                    break
            except ValueError:
                print(_("Invalid input (no integer). Try again...")) 
Example #15
Source File: setup.py    From trelby with GNU General Public License v2.0 6 votes vote down vote up
def copy_scripts(self):
        _build_scripts.copy_scripts(self)

        if "install" in self.distribution.command_obj:
            iobj = self.distribution.command_obj["install"]
            libDir = iobj.install_lib

            if iobj.root:
                libDir = libDir[len(iobj.root):]

            script = convert_path("bin/trelby")
            outfile = os.path.join(self.build_dir, os.path.basename(script))

            # abuse fileinput to replace a line in bin/trelby
            for line in fileinput.input(outfile, inplace = 1):
                if """sys.path.insert(0, "src")""" in line:
                    line = """sys.path.insert(0, "%s/src")""" % libDir

                print line, 
Example #16
Source File: notes.py    From Some-Examples-of-Simple-Python-Script with GNU Affero General Public License v3.0 6 votes vote down vote up
def delnote(self, args):
        self.help = "./notes.py delnote <file_name> <numb_line>"
        if len(sys.argv) < 3:
            sys.exit("[-] Fucking Damn!!\n[?] Use similiar this: " + self.help)

        f_note_out = str(sys.argv[2])
        try:
            for numb, line in enumerate(fileinput.input(f_note_out, inplace=True)): #start index from 0
                if numb == int(sys.argv[3]):
                    continue
                else:
                    sys.stdout.write(line)
            sys.exit("[+] Success delete line <"+sys.argv[3]+"> in file of <"+ f_note_out +">")
        
        except OSError:
            sys.exit("[-] File Doesn't exists!!"+\
                     "\n[?] This your path now: " +str(os.getcwd())+\
                     "\n[?] This files and folders in your path now: " + str(os.listdir('.')) ) 
Example #17
Source File: file_util.py    From tools with GNU General Public License v2.0 6 votes vote down vote up
def in_out(args,multiple_files=False):
    """Open the input/output data streams. If multiple_files is set to
    True, returns an iterator over lines. If set to False, returns an open file.
    This distinction is needed because validator.py checks the newlines property and
    needs to get the input as a file, but the other scripts just need the lines
    so they can work with several files.
    """
    #Decide where to get the data from
    if args.input is None or args.input=="-": #Stdin
        inp=codecs.getreader("utf-8")(os.fdopen(0,"U")) #Switched universal newlines on
    else: #File name given
        if multiple_files:
            inp_raw=fileinput.input(files=args.input,mode="U")
            inp=(line.decode("utf-8") for line in inp_raw)
        else:
            inp_raw=open(args.input,mode="U")
            inp=codecs.getreader("utf-8")(inp_raw)
    #inp is now an iterator over lines, giving unicode strings

    if args.output is None or args.output=="-": #stdout
        out=codecs.getwriter("utf-8")(sys.stdout)
    else: #File name given
        out=codecs.open(args.output,"w","utf-8")
    return inp,out 
Example #18
Source File: fileinput.py    From Computable with MIT License 5 votes vote down vote up
def isfirstline():
    """
    Returns true the line just read is the first line of its file,
    otherwise returns false.
    """
    if not _state:
        raise RuntimeError, "no active input()"
    return _state.isfirstline() 
Example #19
Source File: fileinput.py    From BinderFilter with MIT License 5 votes vote down vote up
def filename():
    """
    Return the name of the file currently being read.
    Before the first line has been read, returns None.
    """
    if not _state:
        raise RuntimeError, "no active input()"
    return _state.filename() 
Example #20
Source File: fileinput.py    From BinderFilter with MIT License 5 votes vote down vote up
def lineno():
    """
    Return the cumulative line number of the line that has just been read.
    Before the first line has been read, returns 0. After the last line
    of the last file has been read, returns the line number of that line.
    """
    if not _state:
        raise RuntimeError, "no active input()"
    return _state.lineno() 
Example #21
Source File: fileinput.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def isstdin():
    """
    Returns true if the last line was read from sys.stdin,
    otherwise returns false.
    """
    if not _state:
        raise RuntimeError, "no active input()"
    return _state.isstdin() 
Example #22
Source File: fileinput.py    From BinderFilter with MIT License 5 votes vote down vote up
def nextfile():
    """
    Close the current file so that the next iteration will read the first
    line from the next file (if any); lines not read from the file will
    not count towards the cumulative line count. The filename is not
    changed until after the first line of the next file has been read.
    Before the first line has been read, this function has no effect;
    it cannot be used to skip the first file. After the last line of the
    last file has been read, this function has no effect.
    """
    if not _state:
        raise RuntimeError, "no active input()"
    return _state.nextfile() 
Example #23
Source File: fileinput.py    From BinderFilter with MIT License 5 votes vote down vote up
def input(files=None, inplace=0, backup="", bufsize=0,
          mode="r", openhook=None):
    """input([files[, inplace[, backup[, mode[, openhook]]]]])

    Create an instance of the FileInput class. The instance will be used
    as global state for the functions of this module, and is also returned
    to use during iteration. The parameters to this function will be passed
    along to the constructor of the FileInput class.
    """
    global _state
    if _state and _state._file:
        raise RuntimeError, "input() already active"
    _state = FileInput(files, inplace, backup, bufsize, mode, openhook)
    return _state 
Example #24
Source File: conftest.py    From MadMax with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def cfg(request):
    from src.tac_cfg import TACGraph
    import src.optimise as optimise  # TODO: Fix this
    with open(request.param) as f:
        disasm = f.read()
    cfg = TACGraph.from_dasm(fileinput.input())
    optimise.fold_constants(cfg)
    cfg.hook_up_jumps()
    yield cfg 
Example #25
Source File: methods.py    From dyc with MIT License 5 votes vote down vote up
def apply(self):
        """
        Over here we are looping over the result of the
        chosen methods to document and applying the changes to the
        files as confirmed
        """
        for method_interface in self._method_interface_gen():
            if not method_interface:
                continue
            fileInput = fileinput.input(method_interface.filename, inplace=True)

            for line in fileInput:
                tmpLine = line
                if self._is_method(line) and ":" not in line:
                    openedP = line.count("(")
                    closedP = line.count(")")
                    pos = 1
                    if openedP == closedP:
                        continue
                    else:
                        while openedP != closedP:
                            tmpLine += fileInput.readline()
                            openedP = tmpLine.count("(")
                            closedP = tmpLine.count(")")
                            pos += 1
                        line = tmpLine

                if self._get_name(line) == method_interface.name:
                    if self.config.get("within_scope"):
                        sys.stdout.write(line + method_interface.result + "\n")
                    else:
                        sys.stdout.write(method_interface.result + "\n" + line)
                else:
                    sys.stdout.write(line) 
Example #26
Source File: detok.py    From fairseq with MIT License 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='')
    parser.add_argument('files', nargs='*', help='input files')
    args = parser.parse_args()

    detok = sacremoses.MosesDetokenizer()

    for line in fileinput.input(args.files, openhook=fileinput.hook_compressed):
        print(detok.detokenize(line.strip().split(' ')).replace(' @', '').replace('@ ', '').replace(' =', '=').replace('= ', '=').replace(' – ', '–')) 
Example #27
Source File: interactive.py    From fairseq with MIT License 5 votes vote down vote up
def buffered_read(input, buffer_size):
    buffer = []
    with fileinput.input(files=[input], openhook=fileinput.hook_encoded("utf-8")) as h:
        for src_str in h:
            buffer.append(src_str.strip())
            if len(buffer) >= buffer_size:
                yield buffer
                buffer = []

    if len(buffer) > 0:
        yield buffer 
Example #28
Source File: fileinput.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def _test():
    import getopt
    inplace = 0
    backup = 0
    opts, args = getopt.getopt(sys.argv[1:], "ib:")
    for o, a in opts:
        if o == '-i': inplace = 1
        if o == '-b': backup = a
    for line in input(args, inplace=inplace, backup=backup):
        if line[-1:] == '\n': line = line[:-1]
        if line[-1:] == '\r': line = line[:-1]
        print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
                                   isfirstline() and "*" or "", line)
    print "%d: %s[%d]" % (lineno(), filename(), filelineno()) 
Example #29
Source File: fileinput.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def __getitem__(self, i):
        if i != self.lineno():
            raise RuntimeError, "accessing lines out of order"
        try:
            return self.next()
        except StopIteration:
            raise IndexError, "end of input reached" 
Example #30
Source File: fileinput.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def input(files=None, inplace=0, backup="", bufsize=0,
          mode="r", openhook=None):
    """Return an instance of the FileInput class, which can be iterated.

    The parameters are passed to the constructor of the FileInput class.
    The returned instance, in addition to being an iterator,
    keeps global state for the functions of this module,.
    """
    global _state
    if _state and _state._file:
        raise RuntimeError, "input() already active"
    _state = FileInput(files, inplace, backup, bufsize, mode, openhook)
    return _state