Results of commands are not displayed when run from a notebook cell.
From IPython notebook:
os.system("pwd")
0
<-- no errors
From IPython invoked from CLI:
In [15]: os.system("pwd")
/Users/joe
Out[15]: 0
<-- no errors
I expected to see /Users/joe
displayed when command runs from a notebook cell. What's missing?
Thank you, I.
This is explained here :
When you do os.system, it's not capturing stdout/stderr from the new process. In the terminal, this works, because stdout and stderr just go directly to the terminal, without Python ever knowing about them. In the notebook, it doesn't, because the kernel can only forward stdout/stderr that it knows about.
The solution to the problem is to use subprocess
:
>>> import subprocess
>>> subprocess.check_output(["pwd"])
/Users/joe
IPython (Notebook) has a solution for this:
In [1]: %pwd
'/Users/xxx/tmp'
You can also call any shell command:
In [2]: !pwd
'/Users/xxx/tmp'
In the notebook you can also run a whole cell with bash
commands:
In [3]: %%bash
pwd
ls
'/Users/xxx/tmp'
file1.txt
file2.txt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.