简体   繁体   中英

Can I tell Python to ignore the rest of a file and/or exit without raising an exception as if the end of file was reached?

When I execute a Python script(*) and the end of the file is reached, I get back to the command prompt without any additional messages displayed. I would like to know whether there's a statement I can insert somewhere in the source file in order to "exit the file" (end interpretation & compilation) at that point, ie , ignore its contents from there up to the end of the file (or alternatively, to ignore a large region as I could do in C using an #if 0 preprocessor directive and the corresponding #endif ), so I could leave notes and code snippets etc. below that point while I'm working on the earlier part of the file.

When I use quit() , exit() , raise SystemExit(...) etc., all of these throw an exception leading to a "Traceback" message. Is there something like \\endinput in (La)TeX which tells the interpreter to simply ignore the rest of the file, as if the end-of-file was already reached, or the cpp directives #if 0 ... #endif ?

The question "How to exit... without Traceback..." is many times asked and answered here on SO, but the answer is always "you can't"; "it must be that way to allow cleanup / debugging ..." (some mention os._exit() then others say "no-no because of incomplete cleanup"). Maybe this refers to exiting from "within something", but maybe I'm in that case because my file is read by some other python function. So I'm rather looking for a command which says "Here's the end of this file!" or "Ignore the subsequent lines of the input file up to the end (or up to the corresponding #endignore directive is such exists.)

PS: I know that I could put the rest of the file within """...""" , but that would work only up to where I already have a multi-line comment in my "scratch area". Yes, I could [and do] use """ for multi-line commands and ''' to "comment out" the rest of the file. But I consider that as a workaround, and not answer to my question whether such a command or directive exists.

(*) To explain further my need for such a solution: I have this problem on pythonanywhere.com which I have to use for professional (educational) reasons. Clicking on "Run" executes a command _pa_run("filename") on their server (probably a custom command made by them), maybe that's why exit() or sys.exit() yield that Traceback.

EDIT: Upon request, I'll add a specific example (although unrealistic, for sake of brevity):

def Newton(f,x0,eps,N):
    """here I implement Newton's method"""
    #(...) iterations go here (...)
    return x
def f(x): #function for testing
   return ...

quit() # Unfortunately this raises a Traceback, at least when the file is "Run" 
# on pythonanywhere.com. I'd like to avoid this. I would simply like everything
# to be ignored after this point, let's say "for convenience", to simplify.
# I'd like to know whether this is possible, in the given configuration.

def f(x):# this is another function for testing
   return [something else]
[...] # another formula to try. This is just a snippet and might not compile.
def Newton(...):# the old version. Not yet trashed because maybe needed.
      # Would have to rename this if the whole file is read by the compiler.

# Below follow more routines which are part of the final version of this file, 
# but I don't want to compile all of them each time, while I fiddle around with
# the latest addition, for now put the beginning of the file.
# OTOH I would like to have that code in the same file for easier copy-paste in
# case I need some parts of it while developing the new stuff at top of file.

Python is not like LaTeX though. It is possible to write a Python script in a style where there are no functions and no if __name__ == "__main__": so its flow of execution is from top to bottom, but that doesn't mean it's similar to LaTeX.

I would like to know whether there's a command to "exit" (end parsing / execution of) the script before the end of the file

I think your mental model of how a Python script is interpreted and executed is incongruent with what actually happens. First off, parsing the script isn't same as execution of it, so you need to consider them separately.

It seems like the LaTeX syntax being similar to a programming language is confusing you to search for a concept similar to \\endinput where none exists. I don't think there is a way to stop the "parsing" of the script at any point and if you want part of the script not to "execute", you'll either need to call something like exit or return before you reach that part or wrap it in a comment block.

In sys module, exit function is there. It will smoothly exit from the code.

Try using sys.exit(0)

Treating this as an xy-problem

You want to do literate python programming

Literate Programming(LP)

My simple(istic) definition of LP is that LP inverts the "defaultiness" of code and comment.

Take C for example:

  • If you choose // to comment you need to put it n times for n lines
  • If you choose /* you've to be careful to avoid inside */

Why not say everything is a comment except lines starting with some character? This is the LP option. eg LiterateHaskell uses >

Python Literate programming

I don't really recommend these options since a literate programming model needs better to be supported by the language itself. See literate haskell

LP systems

A better option is to use an LP system. Eg

  • Jupyter
  • Emacs -> org mode -> babel

Taking your question "literally"(!!)

The problem is parsing — since python parses the whole program file before any execution you will almost certainly get SyntaxErrors if you throw random text at the interpreter. Python gives enough hooks for customizing the interpreter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM