Note that there are some explanatory texts on larger screens.

plurals
  1. POPython: some newbie questions on sys.stderr and using function as argument
    text
    copied!<p>I'm just starting on Python and maybe I'm worrying too much too soon, but anyways...</p> <pre><code>log = "/tmp/trefnoc.log" def logThis (text, display=""): msg = str(now.strftime("%Y-%m-%d %H:%M")) + " TREfNOC: " + text if display != None: print msg + display logfile = open(log, "a") logfile.write(msg + "\n") logfile.close() return msg def logThisAndExit (text, display=""): msg = logThis(text, display=None) sys.exit(msg + display) </code></pre> <p><strong>That is working</strong>, but I don't like how it looks. Is there a better way to write this (maybe with just 1 function) and is there <a href="https://stackoverflow.com/questions/983201/python-and-sys-argv">any other thing</a> <em>I should be concerned under exiting</em>?</p> <hr> <p>Now to some background (but not about <a href="http://code.google.com/p/trefnoc/" rel="nofollow noreferrer">trefnoc</a>)...</p> <p>Sometimes I will call <code>logThis</code> just to log and display. Other times I want to call it and exit. Initially I was doing this:</p> <pre><code>logThis ("ERROR. EXITING") sys.exit() </code></pre> <p>Then I figured that wouldn't properly set the <code>stderr</code>, thus the current code shown on the top.</p> <p>My first idea was actually passing "sys.exit" as an argument, and defining just <code>logThis ("ERROR. EXITING", call=sys.exit)</code> defined as following (showing just the relevant differenced part):</p> <pre><code>def logThis (text, display="", call=print): msg = str(now.strftime("%Y-%m-%d %H:%M")) + " TREfNOC: " + text call msg + display </code></pre> <p>But that obviously didn't work. I think Python doesn't store functions inside variables. I couldn't (<em>quickly</em>) find anywhere if Python can have <em>variables taking functions</em> or not! Maybe using an <code>eval</code> function? I really always try to avoid them, tho. Sure I thought of using <code>if</code> instead of another <code>def</code>, but that wouldn't be any better or worst.</p> <p>Anyway, any thoughts?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload