1

I recently encountered the common "unexpected indent" problem when trying to evaluate python code by copying them from PyDev and Emacs into a python interpreter.

After trying to fix tab/spaces and some searches, I found the cause in this answer:

This error can also occur when pasting something into the Python interpreter (terminal/console).

Note that the interpreter interprets an empty line as the end of an expression, so if you paste in something like

def my_function():
    x = 3

    y = 7

the interpreter will interpret the empty line before y = 7 as the end of the expression ...

, which is exactly the case in my situation. And there is also a comment to the answer which points out a solution:

key being that blank lines within the function definition are fine, but they still must have the initial whitespace since Python interprets any blank line as the end of the function

But the solution is impractical as I have many empty lines that are problematic for the interpreter. My question is:

Is there a method/tool to automatically insert the right number of initial whitespaces to empty lines so that I can copy-and-paste my code from an editor to an interpreter?

thor
  • 21,418
  • 31
  • 87
  • 173
  • Is there a reason why you don't save your scripts and run them from the command line, and thus circumvent the issue? The commandline interpreter really isn't the best tool for larger chunks of code. – jesper_bk Mar 27 '18 at 07:57
  • you can use pycharm community edition to it is a IDE https://www.jetbrains.com/pycharm-edu/download/ it provides you with editor and you can configure you interpreter in it. – toheedNiaz Mar 27 '18 at 07:58
  • 1
    @jesper_bk I use qgis's python interpreter, which has some bindings to GUI functions that are not available from general interfaces like the command line or eclipse. – thor Mar 27 '18 at 08:00

1 Answers1

5

Don't bother with inserting spaces. Tell the interpreter to execute a block of text instead:

>>> exec(r'''
<paste your code>
''')

The r''' ... ''' tripple-quoted string preserves escapes and newlines. Sometimes (though in my experience, rarely) you need to use r""" ... """ instead, when the code block contains tripple-quoted strings using single quotes.

Another option is to switch to using IPython to do your day-to-day testing of pasted code, which handles pasted code with blank lines natively.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343