Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 939
xxyao Avatar asked Jul 13 '26 06:07

xxyao


1 Answers

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')
like image 107
ShadowRanger Avatar answered Jul 14 '26 20:07

ShadowRanger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!