Pasting in terminal with indentation
Mia Lopez
I am pasting a python code in Ubuntu Terminal. However, the code contains for loops for which indentation is necessary. Is there a way to paste the code maintaining indentation. I remember there is a command like paste"some character" which directly pastes with indentation. But I cant find it online.
Can somebody suggest a way or remind me of the command?
41 Answer
You're better off pasting code to python interpreter. In the shell, however, you can start here-doc redirection with python <<EOF, paste code, and close it with EOF. Like so:
$ python3 <<EOF
> for i in range(5):
> print(i)
> EOF
0
1
2
3
4Of course, make sure you're using proper Python version and your code syntax matches that.
If you wanna get creative, install xclip package to access clipboard contents programmatically ( installation is done via sudo apt-get install xclip) and create the following function in your .bashrc, then source it:
pyfromclip(){ python3 < <(xclip -o -sel clip); }This function uses process substitution < <() feature of bash, and redirects output of xclip, which releases clipboard contents to its stdout stream, into python's stdin stream.
$ cat ./hello_world.py
d = { "Hello": 1, "World": 2 }
for key,value in d.items(): print(key,value)
$ xclip -sel clip ./hello_world.py
$ # We copied into clipboard, so now let's run it
$ pyfromclip
Hello 1
World 2