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.
Related
I'm beginner to both bash and python.
I'm working in Ubuntu env.
to be short, I've created a shell script 'format_data.sh' that runs python file 'proc_ko.py' within it.
#!/bin/bash
...
python path/to/python/file/proc_ko.py
...
And the python file 'proc_ko.py' imports a module called khaiii
from khaiii import KhaiiiApi
api = KhaiiiApi()
...
But when I try to execute 'format_data.sh', I get this import error from python file.
Traceback (most recent call last):
File "media/sf_projet/pe/pe/PROGRAMME/SCRIPTS/proc_ko.py", line 5, in
from khaiii import KhaiiiApi
ImportError: No module named khaiii
which doesn't occur when I execute python file independently.
Python file 'proc_ko.py' itself doesn't have any error and 'khaiii' is well installed.
so I don't understand why import error occurs only through the shell script.
If u need more details to figure out, I'll be happy to provide. Thanks in advance for help.
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.
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.
I have the following script test.py:
import pathlib, os
path = "C:\\Windows"
pathparent = pathlib.Path("C:\\Windows").parent
if os.path.exists(pathparent):
print("path exists")
and when I execute it in Spyder IDE I get this:
path exists
when I run it from the command prompt (python test.py) I get this:
Traceback (most recent call last):
File "test.py", line 6, in <module>
if os.path.exists(pathparent):
File "C:\Anaconda3\lib\genericpath.py", line 19, in exists
os.stat(path)
TypeError: argument should be string, bytes or integer, not WindowsPath
Any idea why I get the different results?
Note: I know that wrapping pathparent in str() will make the if statement succeed, but what I want to know is why the the two environments yield different results.
os.path.exists() started accepting path objects in Python 3.6 and your problem is occuring in your cmd prompts as it is running Python 3.5, change it to 3.6 to fix your problem.
Im a newbie to python and starting to learn Ninja IDE seemed good. but when trying to import "telnetlib" module from within the NINJA I get error:
>>> import telnetlib
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named telnetlib
>>>
I successfully import modules like "sys" and "time".
Results of sys.path:
>>> sys.path
['C:\\Program Files (x86)\\Ninja\\Ninja.exe']
>>>
I already have C:\python27\ folders in path and also created a system environment variable called PYTHONPATH as mentioned here:
How to add to the pythonpath in windows 7?
It Works fine when using python for windows (from python.org).
Thanks