Why doesn't Python remember the initial directory?

andrea crotti andrea.crotti.0 at gmail.com
Mon Aug 20 07:56:42 EDT 2012


2012/8/20 kj <no.email at please.post>:
> In <roy-CA6D77.17031119082012 at news.panix.com> Roy Smith <roy at panix.com> writes> This means that no library code can ever count on, for example,
> being able to reliably find the path to the file that contains the
> definition of __main__.  That's a weakness, IMO.  One manifestation
> of this weakness is that os.chdir breaks inspect.getmodule, at
> least on Unix.  If you have some Unix system handy, you can try
> the following.  First change the argument to os.chdir below to some
> valid directory other than your working directory.  Then, run the
> script, making sure that you refer to it using a relative path.
> When I do this on my system (OS X + Python 2.7.3), the script bombs
> at the last print statement, because the second call to inspect.getmodule
> (though not the first one) returns None.
>
> import inspect
> import os
>
> frame = inspect.currentframe()
>
> print inspect.getmodule(frame).__name__
>
> os.chdir('/some/other/directory') # where '/some/other/directory' is
>                                   # different from the initial directory
>
> print inspect.getmodule(frame).__name__
>
> ...............
>
> % python demo.py
> python demo.py
> __main__
> Traceback (most recent call last):
>   File "demo.py", line 11, in <module>
>     print inspect.getmodule(frame).__name__
> AttributeError: 'NoneType' object has no attribute '__name__'
>
>..

As in many other cases the programming language can't possibly act
safely on all the possible stupid things that the programmer wants to
do, and not understanding how an operating system works doesn't help
either..

In the specific case there is absolutely no use of os.chdir, since you
can:
- use absolute paths
- things like subprocess.Popen accept a cwd argument
- at worst you can chdir back to the previous position right after the
broken thing that require a certain path that you are calling is run



More information about the Python-list mailing list