ConfigParser instance has no attribute '[extension]' - python

I am learning python and I am trying to do a simple task of reading information from a config file.
So using the Python Doc and this similar problem as a reference I created two files.
This is my config file config.ini (also tried config.cfg)
[DEFAULT]
OutDir = path_to_file/
[AUTH]
TestInt = 100
TestStr = blue
TestParse = blua
and this is my python file test.py
import ConfigParser
from ConfigParser import *
config = ConfigParser()
config.read(config.cfg)
for name in config.options('AUTH'):
print name
out = config.get('DEFAULT', 'OutDir')
print 'Output directory is ' + out
however when running the command python test.py I am erroring out and receiving this error
Traceback (most recent call last):
File "test.py", line 7, in <module>
config.read(config.cfg)
AttributeError: ConfigParser instance has no attribute 'cfg'
Note: I thought that meant it the extension couldn't be read so I created the .ini file and changed it in the code and I received the same error but it instead read ...has no attribute 'ini'
I am not sure what I am doing wrong since I am doing the exact same as the python doc and the solution someone used to fix this similar issue.

config.read takes a string as its argument. You forgot to quote the file name, and config was coincidentally the name of a Python object (the module) that potentially could have a cfg attribute. You'd get an entirely different error if you had written config.read(foobarbaz.ini).
The correct line is
config.read('config.cfg') # or 'config.ini', if that's the file name

Related

Sharing variables in python

So I've recently been working on a simple project, and I've used "Jaheim Archibald's Login System" for logging in to my thing. I've found a variable that is the username entered, and I want to share that variable across another script that I'm creating. I've tried using the 'config' module, but it just gives me an attribute error.
EDIT:
Here is the sharing I tried to do:
Loginregister.py:
import config
config.x = userName
Account.py:
import config
print(config.x)
Error:
Traceback (most recent call last):
File "Account.py", line 3, in <module>
print(config.x)
AttributeError: module 'config' has no attribute 'x'

Python inputs from another python file

I have a python file(file1.py) where i have written a script. Now, my friend asked me to keep the inputs in another python file(file2.py) and import the file in file1.py so that its becomes easy to modify the inputs if we keep it seperate file. So i created file2.py, copied the inputs there and saved it. Then i wrote the following line in file1.py: from file2 import * but its throwing error:
TASK [Run the python script]
********************************************************************************************************************************************************************************************************************************* fatal: [automation_server]: FAILED! => {"changed": true, "msg":
"non-zero return code", "rc": 1, "stderr": "Shared connection to
10.242.174.192 closed.\r\n", "stderr_lines": ["Shared connection to 10.242.174.192 closed."], "stdout": "/etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such
file or directory\r\nTraceback (most recent call last):\r\n File
\"/home/bgnanasekaran/.ansible/tmp/ansible-tmp-1591957555.760499-407
182191177023663/download_RI_build.py\", line 8, in \r\n
from file2 import
*\r\nModuleNotFoundError: No module named 'file2'\r\n", "stdout_lines": ["/etc/profile.d/lang.sh: line 19: warning: setlocale:
LC_CTYPE: cannot change locale (UTF-8): No such file or directory",
"Traceback (most recent call last):", " File
\"/home/bgnanasekaran/.ansible/tmp/ansible-tmp-1591957555.760499-407
182191177023663/download_RI_build.py\", line 8, in ", "
from file2 import *", "ModuleNotFoundError: No module named 'file2'"]}
Note: I'll give some example of inputs in file2.py -
name="Suresh"
college="VIT"
Also note: I wrote all these python scripts to make it run with ansible playbook. This script is a part of play in my ansible playbook.
Please help me do this. I want a python file where i can store my python script inputs and use the same file in python script. This is not so related to ansible but more related to python.
you need a configuration file this post might help you or you can create a class and all required variable as a class variable and import the class into your script.
import is for python files only.
If you want to read content of a file you need to open it.
with open('filename', 'r') as handler:
print(handler.readlines())
Is a minimal example
You could also try to use environment varibales, which is a much more common practice when dealing with deployment strategies
import os
VARIABLE = os.getenv('VARIBALE', 'default_value')
Then you run the script with:
VARIABLE=this ./pythonscript.py
Or export the variable into the environment in another way

Getting "global name 'FbxManager' is not defined"

I am working on creating a WebGL interface for which I am trying to convert FBX models to JSON file format in an automated process using python file, convert_fbx_three.py (from Mr. Doob's GitHub project) from command line.
When I try the following command to convert the FBX:
python convert_fbx_three.py Dolpine.fbx Dolpine
I get following errors:
Error in cmd:
Traceback (most recent call last):
File "convert_fbx_three.py", line 1625, in <module>
sdkManager, scene = InitializeSdkObjects()
File "D:\xampp\htdocs\upload\user\fbx\FbxCommon.py", line 7, in InitializeSdkObjects
lSdkManager = KFbxSdkManager.Create()
NameError: global name 'FbxManager' is not defined
I am using Autodesk FBX SDK 2012.2 available here on Windows 7.
Can you please try the following:
import FbxCommon
.
.
.
lSdkManager, lScene = FbxCommon.InitializeSdkObjects()
You probably need to add environment variables pointing to the folder that contains fbx.pyd, FbxCommon.py, and fbxsip.pyd prior to calling anything in those modules.

Python forgetting variable name?

I'm learning Python and I'm have some issues.
I got this error message:
Traceback (most recent call last):
File "main_console.py", line 8, in <module>
from util import Util
File "../utils/util.py", line 13, in <module>
class Util:
File "../utils/util.py", line 73, in Util
config.write(configfile)
NameError: name 'config' is not defined
Following is my code (this is inside a function):
config = ConfigParser.ConfigParser()
for index, list in enumerate(my_list):
config.add_section(str(index))
config.set(str(index), 'id', list.name)
config.set(str(index), 'host', list.host)
# Creating the folder
myFolder = "/etc/element/"
if not os.path.exists(myFolder):
os.makedirs(myFolder)
# Creating the file
filePath = "/etc/element/settings.cfg"
with open(filePath, 'wb') as configfile:
config.write(configfile)
Note: I'm using Sublime Text 3 as IDE. "myFolder" have the same problem a little time ago - if I type filePath = myFolder + '/settings.cfg' I got the same error of "not defined". Finally, I imported ConfigParser as following: import ConfigParser.
Is Python forgetting my variable name or I'm doing something wrong?
It is possible ConfigParser or some other import also defines a config variable that is being used by your config.write().
Sometimes it is safer to just import the functions you need, that way you know exactly what is defined in your file. It means you have to explicitly import everything that you use in other files, but it prevents any unknown duplication in your namespace.
You would do this like:
from ConfigParser import ConfigParser # instead of import ConfigParser
# Then
config = ConfigParser()
Secondly, config is a common variable - try renaming it to something like myConfig and see if it still happens.
configfile is the object that you want to use for write(). You are using a parser to write.
Thanks for replies, but I found the solution.
I go to Nano and edit the file with this error, so I see the indentation is absolutaly wrong. It was just a Sublime text 3 issue, now's solved.

Trouble running a compiled app which includes singleton

I'm having trouble running a compiled app which includes singleton, the .pyw compilation proccess goes just fine, but when I attempt to run the resulting .exe, it writes an error log with the message shown below:
Traceback (most recent call last):
File "main.pyw", line 16, in <module>
File "tendo\singleton.pyc", line 20, in __init__
AttributeError: 'module' object has no attribute '__file__'
this is how I'm calling singleton:
from tendo import singleton
me = singleton.SingleInstance()
The tendo's singleton module makes use of sys.modules['__main__'].__file__ to find the main directory. In py2exe it doesn't exist, that's why you get this error.
You can fix it with this answer. In tendo/singleton.py, line 20 you have:
self.lockfile = os.path.normpath(tempfile.gettempdir() + '/' +
os.path.splitext(os.path.abspath(sys.modules['__main__'].__file__))[0] \
.replace("/","-").replace(":","").replace("\\","-") + '-%s' % flavor_id +'.lock')
Replace with something like this:
path_to_script = get_main_dir() #see linkd answer
self.lockfile = os.path.normpath(tempfile.gettempdir() + '/' + path_to_script
.replace("/","-").replace(":","").replace("\\","-") + '-%s' % flavor_id +'.lock')
Report this as an issue to the author, and/or make a pull request with the fix.

Categories