问题
I know that many of the working directory prompts that work in IPython also work in Spyder as long as they're prefaced by %.
For example, pwd
and ls
work in IPython, but to run the same commands in Spyder they need to be prefaced with a % such as: %pwd
and %ls
.
To change the directory in IPython, I can run the cd command like: cd C:\Users\
... HOWEVER, this doesn't seem to work in Spyder, even when prefaced with a %. Any suggestions?
I know that os.chdir ('C:\\Users\\')
works, just trying to understand why %cd C:\Users\
doesn't...
回答1:
When you run %foo
, that command is run in a new shell instance running as its own process. When that shell exits, changes to its state (such as its working directory) are lost with it; they don't effect the parent Python process that spawned it.
This is the same as how running sh -c 'cd /'
doesn't change your current working directory in shell. (Indeed, running a new process as sh -c "$some_command"
is exactly how the standard-C library call system(some_command)
, and its Python equivalent os.system(some_command)
works).
来源:https://stackoverflow.com/questions/34243948/cd-command-in-ipython-vs-spyder