python类close()的实例源码

test_fileinput.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_zero_byte_files(self):
        t1 = t2 = t3 = t4 = None
        try:
            t1 = writeTmp(1, [""])
            t2 = writeTmp(2, [""])
            t3 = writeTmp(3, ["The only line there is.\n"])
            t4 = writeTmp(4, [""])
            fi = FileInput(files=(t1, t2, t3, t4))

            line = fi.readline()
            self.assertEqual(line, 'The only line there is.\n')
            self.assertEqual(fi.lineno(), 1)
            self.assertEqual(fi.filelineno(), 1)
            self.assertEqual(fi.filename(), t3)

            line = fi.readline()
            self.assertFalse(line)
            self.assertEqual(fi.lineno(), 1)
            self.assertEqual(fi.filelineno(), 0)
            self.assertEqual(fi.filename(), t4)
            fi.close()
        finally:
            remove_tempfiles(t1, t2, t3, t4)
test_fileinput.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_zero_byte_files(self):
        t1 = t2 = t3 = t4 = None
        try:
            t1 = writeTmp(1, [""])
            t2 = writeTmp(2, [""])
            t3 = writeTmp(3, ["The only line there is.\n"])
            t4 = writeTmp(4, [""])
            fi = FileInput(files=(t1, t2, t3, t4))

            line = fi.readline()
            self.assertEqual(line, 'The only line there is.\n')
            self.assertEqual(fi.lineno(), 1)
            self.assertEqual(fi.filelineno(), 1)
            self.assertEqual(fi.filename(), t3)

            line = fi.readline()
            self.assertFalse(line)
            self.assertEqual(fi.lineno(), 1)
            self.assertEqual(fi.filelineno(), 0)
            self.assertEqual(fi.filename(), t4)
            fi.close()
        finally:
            remove_tempfiles(t1, t2, t3, t4)
fixhash.2.py 文件源码 项目:python-3-for-absolute-begs 作者: Apress 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def rewritefile(fip):
    """Input:  fip, filename; expected to live in the
    current directory.  If the first line begins with
    #!, the line is replaced.  If it doesn't, then
    the proper #! line is prepended to the file.
    Existing file modes are preserved (that's what
    the chmod() call does), but the owner of the
    original file may change to whoever is running
    this script; that may be root on a Unix system.
    """
    global pbang
    mode = os.stat(fip)[ST_MODE]
    for line in fileinput.input(fip, inplace = 1):
    if fileinput.isfirstline():
        if line [: 2] == "#!":
        sys.stdout.write(pbang + "\n")
        else:
        sys.stdout.write(pbang + "\n")
        sys.stdout.write(line)
    else:
        sys.stdout.write(line)
    fileinput.close()
    os.chmod(fip, mode)
test_fileinput.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_zero_byte_files(self):
        t1 = t2 = t3 = t4 = None
        try:
            t1 = writeTmp(1, [""])
            t2 = writeTmp(2, [""])
            t3 = writeTmp(3, ["The only line there is.\n"])
            t4 = writeTmp(4, [""])
            fi = FileInput(files=(t1, t2, t3, t4))

            line = fi.readline()
            self.assertEqual(line, 'The only line there is.\n')
            self.assertEqual(fi.lineno(), 1)
            self.assertEqual(fi.filelineno(), 1)
            self.assertEqual(fi.filename(), t3)

            line = fi.readline()
            self.assertFalse(line)
            self.assertEqual(fi.lineno(), 1)
            self.assertEqual(fi.filelineno(), 0)
            self.assertEqual(fi.filename(), t4)
            fi.close()
        finally:
            remove_tempfiles(t1, t2, t3, t4)
completion.py 文件源码 项目:pyimgui 作者: swistakm 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def output(done_count, all_count, badge_output=None):
    result = "%d%% (%s of %s)" % (
        float(done_count)/all_count * 100,
        done_count, all_count
    )

    badge_url = BASE_URL % quote(result)
    badge_md = BADGE_TEMPLATE % badge_url

    if badge_output:
        output_file = fileinput.input(files=(badge_output,), inplace=True)
        try:
            for line in output_file:
                if BADGE_RE.match(line):
                    sys.stdout.write(badge_md + "\n")
                else:
                    sys.stdout.write(line)

        finally:
            fileinput.close()

    click.echo("Estimated: %s" % result)
    click.echo("Badge:     %s" % badge_md)
models.py 文件源码 项目:bob.bio.base 作者: bioidiap 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _read_multi_column_list(self, list_file):
        rows = []
        if not os.path.isfile(list_file):
            raise RuntimeError('File %s does not exist.' % (list_file,))
        try:
            for line in fileinput.input(list_file):
                if line.strip().startswith('#'):
                    continue
                parsed_line = re.findall('[\w/(-.)]+', line)
                if len(parsed_line):
                    # perform some sanity checks
                    if len(parsed_line) not in (2, 3, 4):
                        raise IOError("The read line '%s' from file '%s' could not be parsed successfully!" % (
                            line.rstrip(), list_file))
                    if len(rows) and len(rows[0]) != len(parsed_line):
                        raise IOError(
                            "The parsed line '%s' from file '%s' has a different number of elements than the first parsed line '%s'!" % (
                                parsed_line, list_file, rows[0]))
                    # append the read line
                    rows.append(parsed_line)
            fileinput.close()
        except IOError as e:
            raise RuntimeError("Error reading the file '%s' : '%s'." % (list_file, e))

        # return the read list as a vector of columns
        return rows
linkedin_collect_url.py 文件源码 项目:linkedin_recommend 作者: duggalr2 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def duplicate_checker(x): ##TODO: implement the files with hash table; especially as the list grows really large??
    with open('linkedin_rec_people.txt') as f, open('linkedin_data_collection.txt') as b:
        w = b.readlines()
        b = []
        for line in w: ##TODO: highly inefficient... is their a better way to compare without including last word???
            line = line.split()
            line = line[:-1]
            b.append(' '.join(line))
        for line in fileinput.input('linkedin_rec_people.txt', inplace=True):
            if x in w:
                line = line.replace(x, '')
            sys.stdout.write(line)
            fileinput.close()
            return True
        return False
io_export_ogreDotScene.py 文件源码 项目:spqrel_tools 作者: LCAS 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def close(self):
        self.end_tag( self.root_tag )

## Report Hack
io_export_ogreDotScene.py 文件源码 项目:spqrel_tools 作者: LCAS 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def save_terrain_as_NTF( path, ob ): # Tundra format - hardcoded 16x16 patch format
    info = bake_terrain( ob )
    url = os.path.join( path, '%s.ntf' % clean_object_name(ob.data.name) )
    f = open(url, "wb")
    # Header
    buf = array.array("I")
    xs = ob.collision_terrain_x_steps
    ys = ob.collision_terrain_y_steps
    xpatches = int(xs/16)
    ypatches = int(ys/16)
    header = [ xpatches, ypatches ]
    buf.fromlist( header )
    buf.tofile(f)
    # Body
    rows = info['data']
    for x in range( xpatches ):
        for y in range( ypatches ):
            patch = []
            for i in range(16):
                for j in range(16):
                    v = rows[ (x*16)+i ][ (y*16)+j ]
                    patch.append( v )
            buf = array.array("f")
            buf.fromlist( patch )
            buf.tofile(f)
    f.close()
    path,name = os.path.split(url)
    R = {
        'url':url, 'min':info['min'], 'max':info['max'], 'path':path, 'name':name,
        'xpatches': xpatches, 'ypatches': ypatches,
        'depth':info['depth'],
    }
    return R
io_export_ogreDotScene.py 文件源码 项目:spqrel_tools 作者: LCAS 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def dot_material( self, meshes, path='/tmp', mat_file_name='SceneMaterial'):
        material_files = []
        mats = []
        for ob in meshes:
            if len(ob.data.materials):
                for mat in ob.data.materials:
                    if mat not in mats:
                        mats.append( mat )

        if not mats:
            print('WARNING: no materials, not writting .material script'); return []

        M = MISSING_MATERIAL + '\n'
        for mat in mats:
            if mat is None:
                continue
            Report.materials.append( material_name(mat) )
            if CONFIG['COPY_SHADER_PROGRAMS']:
                data = generate_material( mat, path=path, copy_programs=True, touch_textures=CONFIG['TOUCH_TEXTURES'] )
            else:
                data = generate_material( mat, path=path, touch_textures=CONFIG['TOUCH_TEXTURES'] )

            M += data
            # Write own .material file per material
            if self.EX_SEP_MATS:
                url = self.dot_material_write_separate( mat, data, path )
                material_files.append(url)

        # Write one .material file for everything
        if not self.EX_SEP_MATS:
            try:
                url = os.path.join(path, '%s.material' % mat_file_name)
                f = open( url, 'wb' ); f.write( bytes(M,'utf-8') ); f.close()
                print('    - Created material:', url)
                material_files.append( url )
            except Exception as e:
                show_dialog("Invalid material object name: " + mat_file_name)

        return material_files
io_export_ogreDotScene.py 文件源码 项目:spqrel_tools 作者: LCAS 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def dot_material_write_separate( self, mat, data, path = '/tmp' ):
        try:
            clean_filename = clean_object_name(mat.name);
            url = os.path.join(path, '%s.material' % clean_filename)
            f = open(url, 'wb'); f.write( bytes(data,'utf-8') ); f.close()
            print('    - Exported Material:', url)
            return url
        except Exception as e:
            show_dialog("Invalid material object name: " + clean_filename)
            return ""
io_export_ogreDotScene.py 文件源码 项目:spqrel_tools 作者: LCAS 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def isRotIdentity( self ):
        # if the angle is very close to zero, or the axis is not unit length,
        if abs(self.rot.angle) < 0.0001 or abs(self.rot.axis.length - 1.0) > 0.001:
            # treat it as a zero rotation
            return True
        return False
joystickIdFixer.py 文件源码 项目:SC-Joystick-Configuration 作者: danricho 项目源码 文件源码 阅读 54 收藏 0 点赞 0 评论 0
def replaceInFile(filename, find, replace):
  for line in fileinput.input(filename, inplace=True):
    line = line.replace(find, replace)
    sys.stdout.write(line)
  fileinput.close()
test_fileinput.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def writeTmp(i, lines, mode='w'):  # opening in text mode is the default
    name = TESTFN + str(i)
    f = open(name, mode)
    for line in lines:
        f.write(line)
    f.close()
    return name
test_fileinput.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def close(self):
        self.invocation_counts["close"] += 1
test_fileinput.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_state_is_None(self):
        """Tests that fileinput.close() does nothing if fileinput._state
           is None"""
        fileinput._state = None
        fileinput.close()
        self.assertIsNone(fileinput._state)
test_fileinput.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_state_is_not_None(self):
        """Tests that fileinput.close() invokes close() on fileinput._state
           and sets _state=None"""
        instance = MockFileInput()
        fileinput._state = instance
        fileinput.close()
        self.assertExactlyOneInvocation(instance, "close")
        self.assertIsNone(fileinput._state)
test_fileinput.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def writeTmp(i, lines, mode='w'):  # opening in text mode is the default
    name = TESTFN + str(i)
    f = open(name, mode)
    for line in lines:
        f.write(line)
    f.close()
    return name
test_fileinput.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def close(self):
        self.invocation_counts["close"] += 1
test_fileinput.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_state_is_None(self):
        """Tests that fileinput.close() does nothing if fileinput._state
           is None"""
        fileinput._state = None
        fileinput.close()
        self.assertIsNone(fileinput._state)
test_fileinput.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_state_is_not_None(self):
        """Tests that fileinput.close() invokes close() on fileinput._state
           and sets _state=None"""
        instance = MockFileInput()
        fileinput._state = instance
        fileinput.close()
        self.assertExactlyOneInvocation(instance, "close")
        self.assertIsNone(fileinput._state)
fixhash.2.py 文件源码 项目:python-3-for-absolute-begs 作者: Apress 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def fixdirectory(d):
    dlist = os.listdir(d)
    nfiles = 0
    for i in dlist:
        if i == nm:
        continue
        if len(i)> 4:
            fname = d + "/" + i
        if fname[-3:] == ".py":
            sys.stderr.write("Checking " + fname + "...\n")
            for line in fileinput.input(fname):
            if fileinput.isfirstline():
                if line[: -1] != pbang:
                fileinput.close()
                t = os.access(fname, os.W_OK)
                if t == 0:
                    sys.stderr.write(fname + " is not writable; skipping.\n")
                else:
                    sys.stderr.write("Modifying " + fname + "...\n")
                    rewritefile(fname)
                    nfiles = nfiles + 1
                break
                else:
                fileinput.close()
                break
    return nfiles
test_fileinput.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def writeTmp(i, lines, mode='w'):  # opening in text mode is the default
    name = TESTFN + str(i)
    f = open(name, mode)
    for line in lines:
        f.write(line)
    f.close()
    return name
test_fileinput.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def close(self):
        self.invocation_counts["close"] += 1
test_fileinput.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_state_is_None(self):
        """Tests that fileinput.close() does nothing if fileinput._state
           is None"""
        fileinput._state = None
        fileinput.close()
        self.assertIsNone(fileinput._state)
test_fileinput.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_state_is_not_None(self):
        """Tests that fileinput.close() invokes close() on fileinput._state
           and sets _state=None"""
        instance = MockFileInput()
        fileinput._state = instance
        fileinput.close()
        self.assertExactlyOneInvocation(instance, "close")
        self.assertIsNone(fileinput._state)
ReVerb.py 文件源码 项目:PPRE 作者: MaoYuwei 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def main():
    reverb = Reverb()
    fout_signature = open('../file/signature_ReVerb.txt', 'w+')
    for line in fileinput.input('../file/signature_between.txt'):
        if '***' in line:
            fout_signature.write(line)
        else:
            mark, line = line.split(':', 1)
            tokens = word_tokenize(line.strip())
            tokens_tagged = pos_tag(tokens)
            #print 'tokens_tagger:', tokens_tagged
            pattern_tags = reverb.extract_reverb_patterns_tagged_ptb(tokens_tagged)
            #print 'pattern_tags:', pattern_tags
            if len(pattern_tags) > 0:
                fout_signature.write(mark + ':')
                for i in pattern_tags:
                    s = i[0].lower()
                    fout_signature.write(s + ' ')
                fout_signature.write('\n')
            # if reverb.detect_passive_voice(pattern_tags):
            #     print "Passive Voice: True"
            # else:
            #     print "Passive Voice: False"
            # print "\n"
    print 'signature ending'

    fileinput.close()
    fout_signature.close()

    fout_seed = open('../file/seed_ReVerb.txt', 'w+')
    for line in fileinput.input('../file/seed_between.txt'):
        if '***' in line:
            fout_seed.write(line)
        else:
            mark, line = line.split(':', 1)
            tokens = word_tokenize(line.strip())
            tokens_tagged = pos_tag(tokens)
            #print 'tokens_tagger:', tokens_tagged
            pattern_tags = reverb.extract_reverb_patterns_tagged_ptb(tokens_tagged)
            #print 'pattern_tags:', pattern_tags
            if len(pattern_tags) > 0:
                fout_seed.write(mark + ':')
                for i in pattern_tags:
                    s = i[0].lower()
                    fout_seed.write(s + ' ')
                fout_seed.write('\n')
            # if reverb.detect_passive_voice(pattern_tags):
            #     print "Passive Voice: True"
            # else:
            #     print "Passive Voice: False"
            # print "\n"
    print 'seed ending'

    fileinput.close()
    fout_seed.close()
main.py 文件源码 项目:thunderbolt100k 作者: cuyu 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def init_zshrc():
    import fileinput

    exist_conf = load_conf()
    if exist_conf:
        print('Thunderbolt100k has initialized before, delete the corresponding contents in `~/.zshrc` and try again')
        return

    # Set default settings
    print('Initializing default settings...')
    write_conf('VERSION', __VERSION__, first_write=True)
    for key in constants.DEFAULT_CONFIG:
        write_conf(key, constants.DEFAULT_CONFIG[key])

    # Bind polling command to a custom PL9K element
    write_conf('POWERLEVEL9K_CUSTOM_POLLING', '"thunderbolt100k polling"', without_prefix=True)

    elements_names = ['custom_polling']
    # Set PL9K custom command
    for m in sys.modules['thunderbolt100k.widgets'].modules:
        if m.endswith('__init__.py'):
            continue
        widget_name = os.path.basename(m).replace('.py', '')
        print('Initializing [{0}] widget...'.format(widget_name))
        widget = getattr(sys.modules['thunderbolt100k.widgets'], widget_name)
        write_conf('POWERLEVEL9K_CUSTOM_{0}'.format(widget_name.upper()),
                   '"thunderbolt100k display {0}"'.format(widget_name), without_prefix=True)

        elements_names.append('custom_{0}'.format(widget_name))
        # Ask for extra info for each widgets
        result = widget.user_input()
        for k in result:
            write_conf(k, result[k])

    # Add the custom elements to PL9K
    home = os.path.expanduser("~")
    path = os.path.join(home, '.zshrc')
    for line in fileinput.input(path, inplace=True):
        if line.startswith('POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS'):
            print(line.replace(')', ' {0})'.format(' '.join(elements_names))).rstrip())
        else:
            print(line.rstrip())
    fileinput.close()

    print('Initialization done! Open a new shell session and enjoy the view!')
    print('You may also want to rearrange the widgets locations by editing `POWERLEVEL9K_LEFT_PROMPT_ELEMENTS` and \n' +
          '`POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS` in `~/.zshrc` file')
    print('If you want to set configurations for THUNDERBOLT100K, please refer to https://github.com/cuyu/thunderbolt100k#configuration')


问题


面经


文章

微信
公众号

扫码关注公众号