2

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?

Sergiy Kolodyazhnyy
  • 103,293
  • 19
  • 273
  • 492
mathisbetter
  • 167
  • 1
  • 6
  • I am aware of that possibility. But I am trying to analyze some data for which I need to run the code snippet by snippet because its easier to comprehend the data, in that way (at least for me) – mathisbetter May 24 '18 at 16:47
  • 1
    Can you give an example of the code you are pasting and also tell us which program is running in terminal when you are pasting it? – Sebastian Stark May 24 '18 at 16:49
  • It is basically an analysis of some numbers and some graphs related to them. I am using the basic Ubuntu Terminal – mathisbetter May 24 '18 at 16:50
  • @mathisbetter We need an example of the code so we can try it ourselves. As for the terminal, we need to know what shell you're running in it, like `python`, `python3`, `ipython`, `pypy`, etc. – wjandrea May 24 '18 at 17:31

1 Answers1

2

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
4

Of 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
wjandrea
  • 14,109
  • 4
  • 48
  • 98
Sergiy Kolodyazhnyy
  • 103,293
  • 19
  • 273
  • 492