Can I do a "dir" (OS command) from within the Python shell?

System: Python 3.9 (for the purpose of a tutorial I’m still doing) on Windows 10.

I did some searching and have not found an answer yet. While in the python shell sometimes I want to see a list of files and do “dir” or “dir /o-d” or “dir” with some other switches.

How can I do this without leaving the Python shell and without opening another cmd.exe window?

I try to keep my open windows to a minimum as I already have 10 open windows already.

You can use

import os

os.listdir('/your/path')

See the os.listdir docs. If you wish to glob use glob.

You can also use pathlib.Path.glob - there are examples in the documentation. Also see the recursive rglob.

1 Like

I would also add that you can do this kind of thing very easily by using iPython as a shell - I’ve never used iPython on Windows, so I don’t know how it behaves, but certainly for Linux/Mac OS you can use an iPython session as a kind of system shell, in addition to its normal use as a Python shell. It’s very convenient and saves a lot of time.

1 Like

(Tangent topic on @sr-murthy 's answer), I don’t know whether shell commands work on Windows either, but you should try ipython nevertheless. It greatly enhances the python shell experience on the terminal.

Just to confirm, they do, just like on Linux (within the limitations of the comparatively primitive Windows CLI environment). If you’re purely doing this as a convenience for interactive use, then IPython is probably the best way to go (or if you want to use an IDE, some like Spyder have it built in, and also often have dedicated panes for interacting with system terminals).

NB, instead of having lots of separate windows with the unbearably primitive default Windows console emulator, consider a far more powerful and ergonomic terminal like ConEmu (as I use with Git Bash, or Cmdr which bundles it), or Microsoft’s own Windows Terminal application, all of which include (among other things) full support for tabs and even default sessions.