1

Example, I have this code saved as test.py

import time
for i in range(0, 10):
    print(i)
    time.sleep(3.0)

When I try to run this on ipynb with !python test.py It processed but it doesn't show realtime in output. I want it to be like show 0, then pause 3 seconds and then show 1 .... etc. in output.

typeocean
  • 55
  • 1
  • 10

1 Answers1

2

You may want to try using %run test.py or %run test.py -i in a cell in your notebook.

(See here.)

! sends what you put after it off to a separate temporary shell instance. That instance runs what you sent as process entirely and then upon completion (depending on system) brings the output back to the notebook & closes itself up and cleans up everything.

Actually how it handles things like this can differ on different systems. For example in sessions launched from here by clicking launch binder (select 'Help' > 'Launch Classic Notebook' if you prefer the other interface although the interface choice makes no difference as both behaved same with your code there), I see !python test.py works as you seek.
However, in general it is best not run scripts in notebooks that way as the magic %run command is best used for running scripts inside a notebook as it is more full-featured and uses the environment in which your notebook is served. So on top of maybe not returning output until the end, !python won't necessarily use the same environment.

Wayne
  • 6,607
  • 8
  • 36
  • 93
  • Sorry to ask you again, does magic command have to be run in my local environment? – typeocean Mar 27 '22 at 19:59
  • 1
    You run it in a cell in the notebook for running a script in a notebook. (I edited answer to add that.) That way it will use the environment the presumably is what your notebook sees. The `!` approach doesn't mean necessarily it does. This parallels why there is now `%pip install` & `%conda install` for running inside notebook cells, see [here](https://discourse.jupyter.org/t/why-users-can-install-modules-from-pip-but-not-from-conda/10722/4?u=fomightez). Those insure packages install to the correct environment; anything that uses the exclamation point in front of `pip` or `conda` is outdated. – Wayne Mar 27 '22 at 20:56