I am parsing a file with ini format using configparser module in python 2. I am using configparser instead of ConfigParser so that code is compataible with python 3.
Problem that with python 2 parsed "value " is coming as unicode string as u'value'.
Please note that with python 3 parsed value is same as python2 if I would use ConfigParser instead.
Is there a way to resolve this?
Sample config file:
$ cat test_config
[test]
field = value
Python run
$ python
Python 2.7.14 (default, Nov 2 2017, 17:39:03)
>>> import configparser
>>> config_name = "test_config"
>>>
>>> config_parser = configparser.SafeConfigParser()
>>> config_parser.optionxform = str
>>> config_parser.read(config_name)
>>> config = {}
>>> mode = 'test'
>>> for item_tuple in config_parser.items(mode):
... config[item_tuple[0]] = item_tuple[1]
...
>>> print(config['field'])
value
>>> config['field']
u'value'
>>>
Related
I have a build.properties file like
[directory]
src = src
srcdir = ${src}/fix
srcext = ${srcdir}/extensions
srct = ${srcext}/xyz
my aim is to get the full value of srct i mean it is to be src/fix/extensions/xyz
Is there any way of getting the value of cde? I tried configparser and jproperties but i couldn't get the required output.
You can use ExtendedInterpolation class which implements more advanced syntax.
>>> from configparser import ConfigParser, ExtendedInterpolation
>>>
>>> parser = ConfigParser(interpolation=ExtendedInterpolation())
>>> parser.read("build.properties")
['build.properties']
>>> print(parser["directory"]["srct"])
src/fix/extensions/xyz
If I use xattr on Python on macOS to display a file's comments, it shows extraneous data:
>>> from xattr import xattr
>>> from pprint import pprint
>>> pprint(xattr('tmp.pk.new')[u'com.apple.metadata:kMDItemFinderComment'])
'bplist00_\x10\x0fExample comment\x08\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1a'
>>>
The comment is just 'Example comment', so what is the other data that's being displayed?
The finder comment is saved in a binary property list format, so you have to decode it to access the contents. In Python 3 you can just use the standard library module plistlib:
>>> from plistlib import loads
>>> from xattr import xattr
>>> contents = xattr('tmp.pk.new')['com.apple.metadata:kMDItemFinderComment']
>>> loads(contents)
'Example comment'
If you are still in Python 2, as your code suggests, you have to use an external library, as the buildin plistlib does not support the binary format, for example:
pip install biplist
python
>>> from biplist import readPlistFromString
>>> from xattr import xattr
>>> contents = xattr('tmp.pk.new')['com.apple.metadata:kMDItemFinderComment']
>>> readPlistFromString(contents)
'Example comment'
I load a .pyd file as python module.
Under windows I see a version when I do a right click->Properties->"Details"-Tab
How can I read (in python) the fileversion of this pyd-file?
Exists a function or something in python to read this version?
Using win32api.GetFileVersionInfo:
>>> import win32api
>>> path = r'c:\python27\lib\site-packages\win32\win32api.pyd'
>>> info = win32api.GetFileVersionInfo(path, '\\')
>>> '{}.{}.{}.{}'.format(
... win32api.HIWORD(info['FileVersionMS']),
... win32api.LOWORD(info['FileVersionMS']),
... win32api.HIWORD(info['FileVersionLS']),
... win32api.LOWORD(info['FileVersionLS']))
'2.7.218.0'
I have a trusted remote server that stores many custom Python modules. I can fetch them via HTTP (e.g. using urllib2.urlopen) as text/plain, but I cannot save the fetched module code to the local hard disk. How can I import the code as a fully operable Python module, including its global variables and imports?
I suppose I have to use some combination of exec and imp module's functions, but I've been unable to make it work yet.
It looks like this should do the trick: importing a dynamically generated module
>>> import imp
>>> foo = imp.new_module("foo")
>>> foo_code = """
... class Foo:
... pass
... """
>>> exec foo_code in foo.__dict__
>>> foo.Foo.__module__
'foo'
>>>
Also, as suggested in the ActiveState article, you might want to add your new module to sys.modules:
>>> import sys
>>> sys.modules["foo"] = foo
>>> from foo import Foo
<class 'Foo' …>
>>>
Here's something I bookmarked a while back that covers something similar:
Customizing the Python Import System
It's a bit beyond what you want, but the basic idea is there.
Python3 version
(attempted to edit other answer but the edit que is full)
import imp
my_dynamic_module = imp.new_module("my_dynamic_module")
exec("""
class Foo:
pass
""", my_dynamic_module.__dict__)
Foo = my_dynamic_module.Foo
foo_object = Foo()
# register it on sys
import sys
sys.modules[my_dynamic_module.__name__] = my_dynamic_module
I recently encountered trying to do this while trying to write unit tests for source code examples I put into a project's readme (I wanted to avoid just linking to small files or duplicating the text in a way that could get out of sync).
I came up with the following
import sys
import types
from importlib import import_module
def compile_and_install_module(module_name: str, source_code: str) -> types.ModuleType:
"""Compile source code and install it as a module.
End result is that `import <module_name>` and `from <module_name> import ...` should work.
"""
module = types.ModuleType(module_name, "Module created from source code")
# Execute source in context of empty/fake module
exec(source_code, module.__dict__)
# Insert fake module into sys.modules. It's now a real module
sys.modules[module_name] = module
# Imports should work now
return import_module(module_name)
And a quick example of how you can use it
$ cat hello.py
def foo():
print("Hello world")
bar = 42
$ python
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from compile import compile_and_install_module
>>> compile_and_install_module("hello", open("hello.py").read())
<module 'hello'>
>>> import hello
>>> hello.foo()
Hello world
>>> from hello import bar
>>> bar
42
You can remove the return value and import_lib import if you
Lets say I have path to a module in a string module_to_be_imported = 'a.b.module'
How can I import it ?
>>> m = __import__('xml.sax')
>>> m.__name__
'xml'
>>> m = __import__('xml.sax', fromlist=[''])
>>> m.__name__
'xml.sax'
You can use the build-in __import__ function. For example:
import sys
myconfigfile = sys.argv[1]
try:
config = __import__(myconfigfile)
for i in config.__dict__:
print i
except ImportError:
print "Unable to import configuration file %s" % (myconfigfile,)
For more information, see:
Python Documentation
Python.org - [Python Wpg] Import a module using a string
x = __import__('a.b.module', fromlist=[''])
Reference