Search code examples
pythonpython-3.xpycharmcd

Cannot use 'cd' command in Python console


I want to change directory using 'cd' command in PyCharm's python console. It works all the time until I bought a new PC.

Environment is Python 3.7; Pycharm 2019.1.1. I google it and some guys told me to use os.chdir() but I want to use 'cd' because it is easy to use.

The error report is:

NameError: name 'cd' is not defined

enter image description here

Thanks :)


Solution

  • cd is not a Python command. You can't use it unless you're running in a non-standard interpreter that provides access to it. Even if you could use it, running cd in a subshell (which is how most other interpreters expose shell commands) wouldn't change the working directory for the Python session you're in.

    If you use an alternate interpreter/interpreter wrapper like ipython, yes, it has cd built-in the way you'd expect it to function.

    But if you're on the bog standard Python interpreter, just use os.chdir. You can always alias it to something shorter if you like, e.g.

    >>> from os import chdir as cd
    >>> cd('foo/bar')