Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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).

like image 228
Nadav Har'El Avatar asked Oct 29 '25 02:10

Nadav Har'El


1 Answers

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

print(1)
"""
@$@(% # this is not correct Python
blah
dee
blah
blah
"""
like image 101
Fred Larson Avatar answered Oct 30 '25 16:10

Fred Larson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!