Ask Your Question
1

Obtain the script dirname interactively from wing IDE.

asked 2022-05-16 04:42:30 -0500

hongyi-zhao's avatar

updated 2022-05-19 14:29:13 -0500

I have a python script in the following location:

 $ realpath pymatgen-affine_matrix.py 
/home/werner/pymatgen-gap-affine_matrix/pymatgen-affine_matrix.py

When I use this script to do some development work in the wing IDE, it's convenient to read some related files on the system based on the directory location of this script. For this purpose, I try to use the following code snippet in this script:

import os,sys
script_dirname1=os.path.dirname(os.path.realpath(__file__))
script_dirname2=os.path.dirname(os.path.abspath(sys.argv[0]))
print(script_dirname1)
print(script_dirname2)

But the above code snippet doesn't work while running them interactively with wing IDE:

import os,sys
script_dirname1=os.path.dirname(os.path.realpath(__file__))
script_dirname2=os.path.dirname(os.path.abspath(sys.argv[0]))
Traceback (most recent call last):
  Python Shell, prompt 8, line 2
builtins.NameError: name '__file__' is not defined
print(script_dirname1)
Traceback (most recent call last):
  Python Shell, prompt 9, line 1
builtins.NameError: name 'script_dirname1' is not defined
print(script_dirname2)
/home

I want to know if there are any clever methods to solve this problem.

P.S. I have understood the problem according to the comments here:

I think what you want to do is run in the debugger, set a breakpoint on the last line, and use the Debug Probe. Evaluating in the Python Shell is (roughly) the equivalent of copying the text from the file and then pasting it into the Python Shell so there's no __file__ set.

We plan to add an option to the debugger to stop just before the program exits.

Cheers,

John

Regards, HZ

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-05-16 10:15:46 -0500

This snippet doesn't work in the interactive shell because the interactive shell isn't executing code from a file and thus doesn't set the __file__ variable (__file__ is set to the filename where the code comes from). My suggestion is to always run code using __file__ in the debugger (or from the command line). You can also set __file__ in the interactive shell via a simple __file__ = '/path/to/file.py' before executing the snippet.

edit flag offensive delete link more

Comments

Nice trick. Got it. Thank you very much.

hongyi-zhao's avatar hongyi-zhao  ( 2022-05-16 18:45:02 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

2 followers

Stats

Asked: 2022-05-16 04:42:30 -0500

Seen: 29 times

Last updated: May 19