zlpython
zlpython

Reputation: 29

different result from F5 and F9 when running the os.path.realpath

I feel very confused about os.path.realpath(os.path.dirname(sys.argv[0]))

Here is my confusion:

(1) If I open my script in spyder (the first time) and run the selected lines below (F9):

import os
import sys
dir_path = os.path.realpath(os.path.dirname(sys.argv[0]))

It returns:

dir_path = C:\Python27\lib\site-packages\spyderlib\widgets\externalshell

which is not the result I want.

(2) However, if I run my whole script (F5), I can get what I expect (which is the current directory of my script):

dir_path = C:\Users\abc\Desktop\py

(3) Additionally if I:

  1. Run the whole script,
  2. %reset variables,
  3. Run the same selected lines as before,

I can still get the current directory of my script, as long as I don't exit spyder:

dir_path = C:\Users\abc\Desktop\py

Gould anyone please explain something on this? It will be very appreciated. Thank you a lot!

Upvotes: 1

Views: 129

Answers (1)

progmatico
progmatico

Reputation: 4964

To get your current complete pathname you can use

os.path.realpath(os.path.curdir)

As for the confusion, print the sys.argv to inspect it. Its content can hold different values, depending on how your script has been called. If I just enter into the python interpreter it holds a list with an empty string, but if I call python myscript.py, it will hold the script name followed by any arguments.

Upvotes: 1

Related Questions