python NameError: global name '__file__' is not defined - python

When I run this code in python 2.7, I get this error:
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\pyutilib.subprocess-3.5.4\setup.py", line 30, in <module>
long_description = read('README.txt'),
File "C:\Python26\Lib\site-packages\pyutilib.subprocess-3.5.4\setup.py", line 19, in read
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
NameError: global name '__file__' is not defined
code is:
import os
from setuptools import setup
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(name="pyutilib.subprocess",
version='3.5.4',
maintainer='William E. Hart',
maintainer_email='wehart#sandia.gov',
url = 'https://software.sandia.gov/svn/public/pyutilib/pyutilib.subprocess',
license = 'BSD',
platforms = ["any"],
description = 'PyUtilib utilites for managing subprocesses.',
long_description = read('README.txt'),
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: Microsoft :: Windows',
'Operating System :: Unix',
'Programming Language :: Python',
'Programming Language :: Unix Shell',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Software Development :: Libraries :: Python Modules'],
packages=['pyutilib', 'pyutilib.subprocess', 'pyutilib.subprocess.tests'],
keywords=['utility'],
namespace_packages=['pyutilib'],
install_requires=['pyutilib.common', 'pyutilib.services']
)

This error comes when you append this line os.path.join(os.path.dirname(__file__)) in python interactive shell.
Python Shell doesn't detect current file path in __file__ and it's related to your filepath in which you added this line
So you should write this line os.path.join(os.path.dirname(__file__)) in file.py. and then run python file.py, It works because it takes your filepath.

I had the same problem with PyInstaller and Py2exe so I came across the resolution on the FAQ from cx-freeze.
When using your script from the console or as an application, the functions hereunder will deliver you the "execution path", not the "actual file path":
print(os.getcwd())
print(sys.argv[0])
print(os.path.dirname(os.path.realpath('__file__')))
Source:
http://cx-freeze.readthedocs.org/en/latest/faq.html
Your old line (initial question):
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
Substitute your line of code with the following snippet.
def find_data_file(filename):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = os.path.dirname(__file__)
return os.path.join(datadir, filename)
With the above code you could add your application to the path of your os, you could execute it anywhere without the problem that your app is unable to find it's data/configuration files.
Tested with python:
3.3.4
2.7.13

I've run into cases where __file__ doesn't work as expected. But the following hasn't failed me so far:
import inspect
src_file_path = inspect.getfile(lambda: None)
This is the closest thing to a Python analog to C's __FILE__.
The behavior of Python's __file__ is much different than C's __FILE__. The C version will give you the original path of the source file. This is useful in logging errors and knowing which source file has the bug.
Python's __file__ only gives you the name of the currently executing file, which may not be very useful in log output.

change your codes as follows! it works for me.
`
os.path.dirname(os.path.abspath("__file__"))

If you're using the code inside a .py file: Use
os.path.abspath(__file__)
If you're using the code on a script directly or in Jupyter Notebooks:
Put the file inside double-quotes.
os.path.abspath("__file__")

Are you using the interactive interpreter? You can use
sys.argv[0]
You should read: How do I get the path of the current executed file in Python?

If all you are looking for is to get your current working directory os.getcwd() will give you the same thing as os.path.dirname(__file__) as long as you have not changed the working directory elsewhere in your code. os.getcwd() also works in interactive mode.
So
os.path.join(os.path.dirname(__file__))
becomes
os.path.join(os.getcwd())

You will get this if you are running the commands from the python shell:
>>> __file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
You need to execute the file directly, by passing it in as an argument to the python command:
$ python somefile.py
In your case, it should really be python setup.py install

If you're exec'ing a file via command line, you can use this hack
import traceback
def get_this_filename():
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
filename = traceback.extract_tb(exc_traceback)[-1].filename
return filename
This worked for me in the UnrealEnginePython console, calling py.exec myfile.py

if you are using jupyter notebook like:
MODEL_NAME = os.path.basename(file)[:-3]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-10-f391bbbab00d> in <module>
----> 1 MODEL_NAME = os.path.basename(__file__)[:-3]
NameError: name '__file__' is not defined
you should place a ' ! ' in front like this
!MODEL_NAME = os.path.basename(__file__)[:-3]
/bin/bash: -c: line 0: syntax error near unexpected token `('
/bin/bash: -c: line 0: `MODEL_NAME = os.path.basename(__file__)[:-3]'
done.....

I'm having exacty the same problem and using probably the same tutorial. The function definition:
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
is buggy, since os.path.dirname(__file__) will not return what you need. Try replacing os.path.dirname(__file__) with os.path.dirname(os.path.abspath(__file__)):
def read(*rnames):
return open(os.path.join(os.path.dirname(os.path.abspath(__file__)), *rnames)).read()
I've just posted Andrew that the code snippet in current docs don't work, hopefully, it'll be corrected.

I think you can do this which get your local file path
if not os.path.isdir(f_dir):
os.mkdirs(f_dir)
try:
approot = os.path.dirname(os.path.abspath(__file__))
except NameError:
approot = os.path.dirname(os.path.abspath(sys.argv[1]))
my_dir= os.path.join(approot, 'f_dir')

Related

configparser.NoSectionError:No section:'XXX'

I want to configure a config. ini and read it. When I run the code in pycharm, it's okay and it returns the result normally. But when I use pyinstaller to package .PY into an .EXE file, it will report an error:
Congparser.NosectionError: No section:'config'
If there are any suggestions, I would be very grateful.
By the way, the. EXE file and. INI file are in the same folder,
I use Python3.7 on Windows10
I'm a Python rookie. I don't know how to solve the error in cmd. I try to output the path in pycharm. The result is very normal.
# coding = gbk
import configparser
import os
curpath = os.path.dirname(os.path.realpath(__file__))
cfgpath = os.path.join(curpath, "config.ini")
print(cfgpath)
print(os.path.realpath(__file__))
conf = configparser.ConfigParser()
conf.read(cfgpath)
items = conf.items('config')
l2 = [items[0][1],items[1][1],items[2][1],items[3][1]]
print(items)
print(l2)
Results in pycharm:
E:\untitled\venv\Custom_formula\config.ini
E:\untitled\venv\Custom_formula\config_data.py
[('server', '127.0.0.1'), ('user', 'sa'), ('pwd', '123456'), ('db', 'test')]
['127.0.0.1', 'sa', '123456', 'test']
Results in CMD:
Traceback (most recent call last):
File "config_data.py", line 25, in <module>
File "configparser.py", line 848, in items
configparser.NoSectionError: No section: 'config'
[9080] Failed to execute script config_data
Thanks for Rolf of Saxony! I solved this problem by change
curpath = os.path.dirname(os.path.realpath(__file__))
to
curpath = os.path.dirname(os.path.realpath(sys.argv[0]))
it turns out that the resluts in pycharm are different from those in EXE,
hopefully this will help more people

pyth error [rtf to xml/html]

I am trying to convert RTF to XML/xhtml using python 3.6.1.
Python Code: https://github.com/brendonh/pyth/blob/master/examples/reading/rtf15.py
import sys
import os.path
from pyth.plugins.rtf15.reader import Rtf15Reader
from pyth.plugins.xhtml.writer import XHTMLWriter
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filename = os.path.normpath(os.path.join(os.path.dirname(__file__),'../../tests/rtfs/sample.rtf'))
doc = Rtf15Reader.read(open(filename, "rb"))
print(XHTMLWriter.write(doc, pretty=True).read())
Error:
Traceback (most recent call last):
File "C:\xx\file1.py", line 14, in <module>
from pyth.plugins.rtf15.reader import Rtf15Reader
File "C:\Python 3.6.1\lib\site-packages\pyth\plugins\rtf15\reader.py", line 594
match = re.match(ur'HYPERLINK "(.*)"', destination)
^
SyntaxError: invalid syntax
May I know how to solve the syntax issue?
Thank you.
Please check the link:
https://pypi.python.org/pypi/pyth/0.6.0
The pyth package is just used for Python 2.x, not worked for Python 3.x version.
PS:
At you sample code, the
print XHTMLWriter.write(doc, pretty=True).read()
is the Python 2.x version, not Python 3.x version. Please check.

Python - Called Script is searching for a file in the Calling Script's directory

I have the following structure
C:\Users\dhiwakarr\workspace\BasicRegressionOnJoker\create&&bkp\script1.py
script1.py will call a function/method defined in script2.py which is located in
C:\Users\dhiwakarr\workspace\basics\script2.py
The problem is script2.py will make use of an XML File (create.xml) which is located in the same folder as script2.py. But when I call this method IN script2.py FROM script1.py. I get the following error,
execute: Error 0x304: Failed to read the input file[createsc.xml].
Traceback (most recent call last):
File "create&&bkp.py", line 19, in <module>
CreateSC.create()
My guess is that the called script (script2.py) is searching for this file in the calling script (script1.py). How do I make the method of script2.py called in script1.py make it search in its own directory ?
UPDATE
script1.sc
import subprocess,sys,getopt,codecs,re,string
import xml.etree.ElementTree as ET
sys.path.insert(0,r'C:\Users\dhiwakarr\workspace\basics')
import Login
import script2
#import script3
try:
#First call the login script to login
print('Login started')
Login.login()
print('Create Subclient')
script2.create()
....
script2.py
import subprocess,sys,os,inspect
from sys import stdout
from _winapi import NULL
def create():
'''
A text file with information about the Client,Storage Policy,Backupset,Subclient & Content of each subclient must be given as seen in sample-create.txt
'''
inputfile = r'C:\Users\dhiwakarr\workspace\create.txt'
finp = open(inputfile,'r')
path = str(os.getcwd())
print('Current Working Path is -- '+path)
for line in finp:
line=line.rstrip('\n')
....
# Creating the Subclient
subprocess.check_call(["C:\\Program Files\\CommVault\\Simpana\\Base\\qoperation.exe", 'execute', '-af', `'createsc.xml',` '-appName', "'File System'",'-clientName', client,'-backupsetName', bset, '-subclientName', scname, '-storagePolicyName', storagepolicy])
else:
See the line subprocess.check_call(["... it fails to read the XML.
The information given is sparse and more code would be helpful.
In general when calling a script from the command line, the base path will be the path, the shell is directed to not the path of calling.
To get information about where your script is looking for files, insert
print os.getcwd()
at the appropriate places (before open or file command). You need to have imported 'os' from the battery pack though.
Furthermore, to get better understanding of the underlying problem, using a
try:
f = open(f)
…
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except:
print "Unexpected error:", sys.exc_info()[0]
raise
might give better understanding of the underlying problem.
your added code information:
Changes of sys.Path (.extend; .insert) will not change the directory for file I/O. sys.Path is directing the module loader only. Use os.chdir or relative paths for file I/O. Use the above print os.getcwd() method get further information about where your code is looking for the .xml file.

Python: Run Script Under Same Window

I am trying to setup a program where when someone enters a command it will run that command which is a script in a sub folder called "lib".
Here is my code:
import os
while 1:
cmd = input(' >: ')
for file in os.listdir('lib'):
if file.endswith('.py'):
try:
os.system(str(cmd + '.py'))
except FileNotFoundError:
print('Command Not Found.')
I have a file: lib/new_user.py But when I try to run it I get this error:
Traceback (most recent call last):
File "C:/Users/Daniel/Desktop/Wasm/Exec.py", line 8, in <module>
exec(str(cmd + '.py'))
File "<string>", line 1, in <module>
NameError: name 'new_user' is not defined
Does anyone know a way around this? I would prefer if the script would be able to be executed under the same window so it doesn't open a completely new one up to run the code there. This may be a really Noob question but I have not been able to find anything on this.
Thanks,
Daniel Alexander
os.system(os.path.join('lib', cmd + '.py'))
You're invoking new_user.py but it is not in the current directory. You need to construct lib/new_user.py.
(I'm not sure what any of this has to do with windows.)
However, a better approach for executing Python code from Python is making them into modules and using import:
import importlib
cmd_module = importlib.import_module(cmd, 'lib')
cmd_module.execute()
(Assuming you have a function execute defined in lib/new_user.py)

keyring module is not included while packaging with py2exe

I am making an app using python 2.7 on windows and keyring-3.2.1 . In my python code on eclipse, I used
import keyring
keyring.set_password("service","jsonkey",json_res)
json_res= keyring.get_password("service","jsonkey")
is working fine as I am storing json response in keyring. But, when I converted python code into exe by using py2exe, it shows import error keyring while making dist. Please suggest how to include keyring in py2exe.
Traceback (most recent call last):
File "APP.py", line 8, in <module>
File "keyring\__init__.pyc", line 12, in <module>
File "keyring\core.pyc", line 15, in <module>
File "keyring\util\platform_.pyc", line 4, in <module>
File "keyring\util\platform.pyc", line 29, in <module>
AttributeError: 'module' object has no attribute 'system'
platform_.py code is :
from __future__ import absolute_import
import os
import platform
def _data_root_Windows():
try:
root = os.environ['LOCALAPPDATA']
except KeyError:
# Windows XP
root = os.path.join(os.environ['USERPROFILE'], 'Local Settings')
return os.path.join(root, 'Python Keyring')
def _data_root_Linux():
"""
Use freedesktop.org Base Dir Specfication to determine storage
location.
"""
fallback = os.path.expanduser('~/.local/share')
root = os.environ.get('XDG_DATA_HOME', None) or fallback
return os.path.join(root, 'python_keyring')
# by default, use Unix convention
data_root = globals().get('_data_root_' + platform.system(), _data_root_Linux)
platform.py code is:
import os
import sys
# While we support Python 2.4, use a convoluted technique to import
# platform from the stdlib.
# With Python 2.5 or later, just do "from __future__ import absolute_import"
# and "import platform"
exec('__import__("platform", globals=dict())')
platform = sys.modules['platform']
def _data_root_Windows():
try:
root = os.environ['LOCALAPPDATA']
except KeyError:
# Windows XP
root = os.path.join(os.environ['USERPROFILE'], 'Local Settings')
return os.path.join(root, 'Python Keyring')
def _data_root_Linux():
"""
Use freedesktop.org Base Dir Specfication to determine storage
location.
"""
fallback = os.path.expanduser('~/.local/share')
root = os.environ.get('XDG_DATA_HOME', None) or fallback
return os.path.join(root, 'python_keyring')
# by default, use Unix convention
data_root = globals().get('_data_root_' + platform.system(), _data_root_Linux)
The issue you're reporting is due to an environment that contains invalid modules, perhaps from an improper installation of one version of keyring over another. You will want to ensure that you've removed remnants of the older version of keyring. In particular, make sure there's no file called keyring\util\platform.* in your site-packages.
After doing that, however, you'll encounter another problem. Keyring loads its backend modules programmatically, so py2exe won't detect them.
To work around that, you'll want to add a 'packages' declaration to your py2exe options to specifically include the keyring.backends package. I invoked the following setup.py script with Python 2.7 to convert 'app.py' (which imports keyring) to an exe:
from distutils.core import setup
import py2exe
setup(
console=['app.py'],
options=dict(py2exe=dict(
packages='keyring.backends',
)),
)
The resulting app.exe will import and invoke keyring.

Categories