Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8410959
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T00:18:55+00:00 2026-06-10T00:18:55+00:00

filename = ‘tempfile’ def tail(filename): fd = open(filename) while True: line = fd.readline() if

  • 0
filename = 'tempfile'

def tail(filename):
    fd = open(filename)
    while True:
        line = fd.readline()
        if not line:
            continue
        else:
            if filename != 'uh':
                yield line
            else:
                print 'Returning f to close the file'
                yield fd


try:
    genObj = tail(filename) 
    valfromgen= genObj.next()
    while valfromgen:
        print valfromgen
        valfromgen= genObj.next()
except:
    traceback.print_exc()
    try:
        fd_Got_Back = genObj.send('uh')
        fd_Got_Back.close()
    except:
        traceback.print_exc()

Intention of the code: I have opened the file in the generator function only and not outside it, but, I want to close that file outside the generator function by using ‘send’ probably.

What I am trying to do: Replicating tail -f from unix.

How I am trying to do:

  1. Open a tempfile in read mode.
  2. If the tempfile has 1 new line written in it (which I’ll keep on writing manually and saving tempfile using notepad), yield the newly written line.

Problem:

The problem is that I’m trying to check how I can close the opened tempfile from this python code if I press Ctrl + C (i.e. SIGTERM) when this Python code runs in command prompt. In order to emulate this, I have opened the tempfile in the tail function, and whenever there is an exception (which will be raised by the system when I press Ctrl + C), the control should go in the 1st except. Then, from here, I’m trying to send a value uh to the generator function tail, so that it should yield the file descriptor of the opened file which I can use to close the opened tempfile.

PS: I expect a solution where I have opened the file in the generator function only and not outside it.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T00:18:57+00:00Added an answer on June 10, 2026 at 12:18 am

    I have figured out the problem where I was stuck and I have come up with this solution:-

    1. When I press Ctrl + C (on Windows), the KeyboardInterrupt actually happens in fd.readline(). So, I just placed a try…except there, so that the generator function yields the file descriptor whenever Ctrl + C is hit. If there is no KeyBoardInterrupt , then, just print a newly read line from tempfile
    2. This file descriptor is checked using isinstance() in the main body, and if it is found to be a file, then, I’m closing the file as well as the generator

    PS: (this KeyboardInterrupt might vary on Linux..probably SigTerm will be raised, but, please check. So, in order to make the code generic, just remove KeyBoard Interrupt and use just normal except)

    import sys,  traceback
    
    filename = 'tempfile'
    
    def tail(filename):
        fd = open(filename)
        while True:
            try:
                line = fd.readline()
            except KeyboardInterrupt:
                print 'keyboard interrupt here'
                yield fd
            if not line:
                continue
            else:
                yield line
    
    
    try:
        genObj = tail(filename) 
        valfromgen= genObj.next()
        while valfromgen:       
            if isinstance(valfromgen, file):
                print 'Closing this file now as `tail` yielded a file descriptor'
                valfromgen.close()
                genObj.close()
                break
            print 'Yielded line: ', valfromgen
            valfromgen= genObj.next()
    
        print 'Just in order to check that things are in order, the following line will raise StopIteration. If it raises, it means we are good.'
        print genObj.next()
    except:
        traceback.print_exc()
    

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

def start(fileName): fileReader = open(fileName) for row in fileReader: print row, if __name__ ==
filename = dict.json def read_dict(filename): file = open( script_dir + filename ) dict =
for filename in os.listdir(.): for line in open(filename).xreadlines(): if foo in line: print line
while executing $expect filename.exp user pwd ip I got the error could not execute
I have a filename that leads to a picture. It is not an embedded
filename = rC:\Dokumente und Einstellungen\sschnei1\Desktop\a.mat print open(filename, r).read().encode(hex) The code above only work for
How to open a filename given in Main's argv[] (say, D:\a.txt) by CreateFile API?
My IDE is having issues with the filename variable on the last line. Can
mp.StartInfo.FileName = E:\\Naag\\execute.bat; mp.StartInfo.UseShellExecute = false; mp.StartInfo.CreateNoWindow = true; mp.StartInfo.RedirectStandardInput = true; mp.StartInfo.RedirectStandardOutput =
f = open(filename, 'r') strings = f.read().lower() I want a python editor/ide that works

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.