9

I am running Jupyter notebook on a server (python 3).

Want to see output of OS command (any OS command - this is just example):

output = os.system("pwd")

When I do print of it:

print (output)

Response is 0.

How to get a simple output (like in CLI)?

Thanks.

Joe
  • 11,983
  • 31
  • 109
  • 183
  • Possible duplicate of [how to show current directory in ipython promp](https://stackoverflow.com/questions/38481506/how-to-show-current-directory-in-ipython-promp) – Fabrizio May 10 '19 at 14:13
  • 1
    This link is not correct. Question is in general to get OS output in iPython (not just PWD or CWD commands).. – Joe May 10 '19 at 14:52

3 Answers3

7

Just found it on internet and wanted to post.

It needs to be:

print(os.popen('ls').read())

(or any other OS command).

This works fine.

Joe
  • 11,983
  • 31
  • 109
  • 183
3
import os

print(os.getcwd())
print(os.system("pwd"))

But this question is a duplicate: how to show current directory in ipython promp

Fabrizio
  • 927
  • 9
  • 20
0

Note that os.system() calls are not the preferred way to run any commands and do not ensure capturing the output (see here for more on this).

The preferred and safer mechanism which will capture the output of commands is subprocess.run() which has a capture_output parameter and returns a CompletedProcess object that has members including stdout and stderr which, if capture_output=True contain the output stream contents.

It is worth mentioning that for portability it is usually better to use the methods from the os, shutil, path & glob libraries, etc. This is because calls such as ls, pwd, dir, etc., will work on some platforms but not others.

Example:

import subprocess

result = subprocess.run(['cwd',], capture_output=True)
# Returns the current directory as a string for processing in result.stdout on Mac/Linux but raises an exception on Windows
print(result.stdout)
result = subprocess.run(['ls', '*.docx'], capture_output=True)
# Returns the *.docx files in the current directory as a string for processing in result.stdout on Mac/Linux but raises an exception on Windows
print(result.stdout)

However:

import pathlib
cwd = pathlib.Path.cwd() # Returns the current directory as a Path object on any platform.
print(cwd)
docs = cwd.glob('*.docx') # Returns an generator giving path for to any docx files in cwd on any platform
print(', '.join(p.name for p in docs)) # Print comma seperated list of filenames

Note that for long running or very verbose calls it is often better to use the subprocess.POpen constructor and communicate or wait.

If you want to start an external process and not wait for it to finish then use the asynco create_subprocess_exec() call instead.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73