Nadav Har'El
Nadav Har'El

Reputation: 13771

How can I tell Python to stop parsing in the middle of the source file?

In many situations I find myself wishing that I could tell Python to ignore a source file from a certain line onward, until the end of the file. Just one example of many is when translating code from another language to Python, function by function: After I translated one function, I want to test it, with the rest of the untranslated code still in the same file, and I hope not to parse it.

In other languages, doing this is easy. Shell has exit 0 which basically causes everything after it to never be parsed. Perl has __END__. C or C++ do not have ignore-until-end-of-file specifically, but it's easy emulate it with a #if 0 at some point and finally #endif at the end of the file.

My question is how can I do this in Python? I tried looking everywhere, and can't seem to find a solution!

To make the question more concrete, consider the following code:

print(1)
exit(0)
@$@(% # this is not correct Python

This program fails. The exit(0) doesn't help because Python still parses everything after it. Not to mention that exit(0) is obviously not the right thing to do in an imported source file (my intention is to stop reading this source file - not to exit the whole program). My question is with what I can replace the "exit(0)" line that will make this program work (print "1" and that's it).

Upvotes: 4

Views: 928

Answers (2)

Mark
Mark

Reputation: 627

You can raise an exception, assuming you have some condition that is met or not

Inside the imported file

print("hi")
my_condition = True
if my_condition:
    raise Exception
print("nope")

and then wrap the import in a try block

try:
    import your_module
except Exception:
    print("source not fully read")

Upvotes: 0

Fred Larson
Fred Larson

Reputation: 62113

Enclose what you don't want parsed in triple quotes:

print(1)
"""
@$@(% # this is not correct Python
blah
dee
blah
blah
"""

Upvotes: 5

Related Questions