Ask Your Question

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 

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

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

import os,sys
Traceback (most recent call last):
  Python Shell, prompt 8, line 2
builtins.NameError: name '__file__' is not defined
Traceback (most recent call last):
  Python Shell, prompt 9, line 1
builtins.NameError: name 'script_dirname1' is not defined

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.



Regards, HZ

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

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/' before executing the snippet.

edit flag offensive delete link more


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



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

Seen: 29 times

Last updated: May 19