NameError: name '__file__' is not defined - python

I am trying to store the path of a script into a variable using:
os.path.abspath(os.path.dirname(__file__))
However, it keeps returning a name '__file__' is not defined error.
here = os.path.dirname(os.path.abspath(__file__))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined

Pretty sure you are running this in a terminal in the interactive Python as it is the only place (I'm aware of) to not have __file__. Also, if it was a script, and it would be the first line of it (according to the error message) it would fail on os is not defined (as you'd not import it).
Try it in the actual script. This should work.

I run into this when testing / debugging classes in Spyder (nearly every day). The fix is easy: define the __file__ variable to the name of the py module you are testing.
In the interpreter type:
__file__ = 'modulename.py'
Then run the script again. This method has never caused an issue for me.

Related

AttributeError: 'PosixPath' object has no attribute 'path'

I have a python script that I'm trying to execute but i'm not sure how it's meant to be executed. I don't program in Python so i'm unfamiliar with the language. Here is the link to the script i'm trying to use. Also, a link the configuration it's using if you wish to see it. All it seems to do for what's relevant here, however, is set my path which I know is correct since other scripts (not linked here) work as expected with the configuration in that file.
Having a look at the script, I believe that the script is meant to be ran with the command line arguments: view, new, init. Thus, I ran the following in my terminal
$ lectures.py new
But I get the following traceback
Traceback (most recent call last):
File "/usr/bin/lectures.py", line 156, in <module>
lectures = Lectures(Path.cwd())
File "/usr/bin/lectures.py", line 60, in __init__
self.root = course.path
AttributeError: 'PosixPath' object has no attribute 'path'
Furthermore, my python version
$ python --version
Python 3.8.1
EDIT:
I wanted to add the reference as well for what I am trying to follow
Going through your code, I think you might mean:
self.root = course
at that line.
Path.cwd() returns:
... the current working directory, that is, the directory from where you run the script.
that is, either a WindowsPath() or a PosixPath object. I believe it is PosixPath for you, and you can verify with:
import os
print(os.name)
# posix -> Linux
# nt -> Windows
This has no attribute path, and this is what your Interpreter tells you.

NameError: name 'runfile' is not defined only when running from script

sima.py
import pyautogui as py
py.alert("Foo")
simaref.py
runfile('E:/Anyagok/Programozas/Python/projekts/gyak/Pyautogui/sima.py',
wdir='E:/Anyagok/Programozas/Python/projekts/gyak/Pyautogui')
These both work when running from Spyder.
sima.py works from cmd as well:
python.exe E:\Anyagok\Programozas\Python\projekts\gyak\Pyautogui\sima.py
But simaref.py doesn't:
E:\Download\PROGIK\ANACONDA>python.exe E:\Anyagok\Programozas\Python\projekts\gyak\Pyautogui\simaref.py
Traceback (most recent call last):
File "E:\Anyagok\Programozas\Python\projekts\gyak\Pyautogui\simaref.py", line 8, in <module>
runfile('E:/Anyagok/Programozas/Python/projekts/gyak/Pyautogui/sima.py', wdir='E:/Anyagok/Programozas/Python/projekts/gyak/Pyautogui')
NameError: name 'runfile' is not defined
Why not?
Edit:
Got the idea of runfile() from: when running code in Spyder, in the console it displays e.g.:
runfile('E:/Anyagok/Programozas/Python/projekts/gyak/Pyautogui/simaref.py', wdir='E:/Anyagok/Programozas/Python/projekts/gyak/Pyautogui')
Working with roganjosh's answer:
Couldn't find where to import the runfile() command, maybe it's something built-in. So I changed simaref.py to the code below, and now it works.
exec(open("E:/Anyagok/Programozas/Python/projekts/gyak/Pyautogui/sima.py").read())

Python import error on Windows: no __path__

OK, trying to track down this issue of running a Python package.
Running on Windows.
Only one version of Python is installed on the computer: 3.4.3
Package has been installed (package name: Willie) (details of installation are more convoluted than usual; can provide steps if necessary)
Package installed at: C:\Python34\Lib\site-packages\willie
Startup script is: C:\Python34\Scripts\willie.py
Error is one of the first lines of the script:
from willie.tools import stderr
If I run willie.py from the command line, I get this error:
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 2218, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python34\Scripts\willie.py", line 15, in <module>
from willie.tools import stderr
File "C:\Python34\Scripts\willie.py", line 15, in <module>
from willie.tools import stderr
ImportError: No module named 'willie.tools'; 'willie' is not a package
The __path__ attribute is supposed to be set automatically when the import function is used, but it doesn't exist, which leads to the program being unable to execute.
C:\Python34\Scripts; is in my Path environment variable.
PYTHONPATH has been set for everything from C:\Python34; to C:\Python34;C:\Python34\Lib;C:\Python34\Lib\site-packages;C:\Python34\Lib\site-packages;C:\Python34\Lib\site-packages\willie;C:\Python34\Lib\site-packages\willie\tools;.
In all cases with these directories, if I try to execute the above import command from the interactive Python prompt, it runs correctly. I can use the stderr function, and examine its __file__ and __path__ fields.
If I add C:\Python34\Scripts; to PYTHONPATH, however, I get the same error as using it from the command line: __path__ doesn't exist, 'willie' is not a package.
I do know that willie.py is being called recursively, somehow, because I can add a print() at the top of the file that runs twice.
Looking for help in figuring out how to make this run. Is almost certainly a configuration issue on my end, but I have no idea what to do to fix it.
First, you absolutely do not want c:\Python34\Scripts in your PYTHONPATH. Files under \Scripts are NOT meant to be importable.
Second, willie does some screwing around to make sure willie.py gets installed to c:\Python34\Scripts\willie (note there is no .py suffix). This is decidedly nonstandard. The only reason this even works is because on Unix machines, the first line of that file is a special "shebang" that tells the Unix program launcher to execute the file using Python. There is no equivalent feature on Windows - naming the file willie with no .py means you simply can't execute it.
So it looks like the module willie is simply not prepared to be installed on Windows systems. (#811 and #822 both refer to weirdness on Windows caused by the nonstandard package setup.)
A standard package setup would have willie.py inside the willie package as willie/main.py and, in the package's setup.py, register willie.main as an "Entry Point" named willie. This incantation would create c:\Python34\Scripts\willie.exe on Windows systems when the package is installed using pip.
I believe the reason for the recursive import is because the second entry in sys.path is the name of the script that is run from the command line. So, it's always finding C:\Python34\Scripts\willie.py when it looks for the module willie which is not the one it needs.
As a workaround, you could try renaming C:\Python34\Scripts\willie.py to C:\Python34\Scripts\run-willie.py

examine the variables when running python script in python environment?

I run my python script after launching Python environment in bash. Then I want to examine a variable defined in my script. But I cannot. I wonder how I can run the script in Python while still being able to examine the variables defined in the script after finish running? Note that I don't want to write the values of the variables to a file or stdout. Thanks!
>>> import myscript
>>> myvar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'myvar' is not defined
You need to say that the variable is part of your import:
import myscript
myscript.myvar
or
from myscript import *
myvar

Unable to debug interactively with Python 2.7

I had asked a question previously on relative paths in python in SO question: How can I access relative paths in Python 2.7 when imported by different modules
The provided answer worked great in all of my scripts and functions. However, when trying to debug the files in IDLE (Python 2.7) it generates run time errors.
Can anyone point me to documentation on using the __file__ notation? Also I would like to understand why IDLE generates errors while running the sample code but running the same file from the command line or double clicking it (for the windows users) does not.
Any help would be greatly appreciated!
Note that I am running Python 2.7 on Windows XP with virtualenv (unactivated during these tests).
Sample Code
import os
import sys
curdir = os.path.dirname(__file__)
sys.path.append(curdir + '/..')
Error
Traceback (most recent call last):
File "C:\MyFile.py", line 3, in `<module>`
curdir = os.path.dirname(`__file__`)
NameError: name '`__file__`' is not defined
__file__ won't be set if you're writing this in the interpretor.
So:
>>> import os, sys
>>> curdir = os.path.dirname(__file__)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
Is expected.
__file__ is the name of the file that was called by the python interpretor - so if you ran this from a script it would work.
$ python curdir.py
$
(The script is exactly the same as what I put into the interpretor, hence no error or output)
From what I've observed using IDLE before, it acts as an interpretor - so it'll run the file in question. However, it wasn't started with that file, so the __file__ is never set.

Categories