Home > Blockchain >  python oneliner, more than one way to do it?
python oneliner, more than one way to do it?

Time:03-22

Interactively one can do:

$ python3 -c "
> import time
> while True:
>   print('Two more weeks')
>   time.sleep(1)
> 
> "
Two more weeks
Two more weeks
Two more weeks
^CTraceback (most recent call last):
  File "", line 5, in 
KeyboardInterrupt

$

Now, is there a feasible way to create and run the "script" above, without actually writing the code to a file?

Note; I believe that indented code and "compound statements" are problematic here!

CodePudding user response:

Assuming you are running bash on Linux you could paste something like this to your shell:

echo """
import time
while 1:
  print('Two more weeks')
  time.sleep(1)
""" | python

With one line you could also do:

echo -e "import time\nwhile 1:\n  print('Two more weeks')\n  time.sleep(1)" | python

CodePudding user response:

In Python3, this monstrosity will fit easily on one line:

$ python3 -c "while True: import time; print('one more week'); time.sleep(1)"
  • Related