如何在App.Config中使用IronPython?

时间:2009-02-15 11:15:12

标签: ironpython

我有一个类库,通常从.net控制台或Web应用程序调用。它集成了各种组件,并依赖于app.config或web.config。

如果我想从脚本(即IronPython)中使用类库,我该如何让脚本使用配置文件?理想情况下,我希望能够在运行脚本时按照惯例选择配置文件(配置文件与脚本文件并排)。

如果可能,我不想更改ipy.exe.config,因为如果没有IronPython的多个副本,这将无法扩展到多个配置?

任何替代方案?

6 个答案:

答案 0 :(得分:3)

我有一个包含代码示例的工作解决方案。看我的博客: http://technomosh.blogspot.com/2012/01/using-appconfig-in-ironpython.html

它需要一个特殊的代理类,它被注入ConfigurationManager。

以下是ConfigurationProxy库的源代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Configuration.Internal;
using System.Xml;
using System.Collections.Specialized;
using System.Reflection;
using System.IO;

namespace IronPythonUtilities
{
    /// <summary>
    /// A custom app.config injector for use with IronPython code that needs configuration files.
    /// The code was taken and modified from the great work by Tom E Stephens:
    /// http://tomestephens.com/2011/02/making-ironpython-work-overriding-the-configurationmanager/
    /// </summary>
    public sealed class ConfigurationProxy : IInternalConfigSystem
    {
        Configuration config;
        Dictionary<string, IConfigurationSectionHandler> customSections;

        // this is called filename but really it's the path as needed...
        // it defaults to checking the directory you're running in.
        public ConfigurationProxy(string fileName)
        {
            customSections = new Dictionary<string, IConfigurationSectionHandler>();

            if (!Load(fileName))
                throw new ConfigurationErrorsException(string.Format(
                    "File: {0} could not be found or was not a valid cofiguration file.",
                    config.FilePath));
        }

        private bool Load(string file)
        {
            var map = new ExeConfigurationFileMap { ExeConfigFilename = file };
            config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

            var xml = new XmlDocument();
            using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read))
                xml.Load(stream);

            //var cfgSections = xml.GetElementsByTagName("configSections");

            //if (cfgSections.Count > 0)
            //{
            //    foreach (XmlNode node in cfgSections[0].ChildNodes)
            //    {
            //        var type = System.Activator.CreateInstance(
            //                             Type.GetType(node.Attributes["type"].Value))
            //                             as IConfigurationSectionHandler;

            //        if (type == null) continue;

            //        customSections.Add(node.Attributes["name"].Value, type);
            //    }
            //}

            return config.HasFile;
        }

        public Configuration Configuration
        {
            get { return config; }
        }

        #region IInternalConfigSystem Members

        public object GetSection(string configKey)
        {
            if (configKey == "appSettings")
                return BuildAppSettings();

            object sect = config.GetSection(configKey);

            if (customSections.ContainsKey(configKey) && sect != null)
            {
                var xml = new XmlDocument();

                xml.LoadXml(((ConfigurationSection)sect).SectionInformation.GetRawXml());
                // I have no idea what I should normally be passing through in the first
                // two params, but I never use them in my confighandlers so I opted not to
                // worry about it and just pass through something...
                sect = customSections[configKey].Create(config,
                                       config.EvaluationContext,
                                       xml.FirstChild);
            }

            return sect;
        }

        public void RefreshConfig(string sectionName)
        {
            // I suppose this will work. Reload the whole file?
            Load(config.FilePath);
        }

        public bool SupportsUserConfig
        {
            get { return false; }
        }

        #endregion

        private NameValueCollection BuildAppSettings()
        {
            var coll = new NameValueCollection();

            foreach (var key in config.AppSettings.Settings.AllKeys)
                coll.Add(key, config.AppSettings.Settings[key].Value);

            return coll;
        }

        public bool InjectToConfigurationManager()
        {
            // inject self into ConfigurationManager
            var configSystem = typeof(ConfigurationManager).GetField("s_configSystem",
                                            BindingFlags.Static | BindingFlags.NonPublic);
            configSystem.SetValue(null, this);

            // lame check, but it's something
            if (ConfigurationManager.AppSettings.Count == config.AppSettings.Settings.Count)
                return true;

            return false;
        }
    }
}

以下是如何从Python加载它:

import clr
clr.AddReferenceToFile('ConfigurationProxy.dll')

from IronPythonUtilities import ConfigurationProxy

def override(filename):
    proxy = ConfigurationProxy(filename)
    return proxy.InjectToConfigurationManager()

最后,一个用法示例:

import configproxy
import sys

if not configproxy.override('blogsample.config'):
    print "could not load configuration file"
    sys.exit(1)

import clr
clr.AddReference('System.Configuration')
from System.Configuration import *
connstr = ConfigurationManager.ConnectionStrings['TestConnStr']
print "The configuration string is {0}".format(connstr)

答案 1 :(得分:2)

您可以查看System.Configuration.ConfigurationManager课程。更具体地说,OpenMappedExeConfiguration方法将允许您加载您选择的任何.config文件。这将为您提供一个Configuration对象,该对象公开标准AppSettins,ConnectionStrings,SectionGroups和Sections属性。

此方法要求您将配置文件的名称作为命令行参数传递给脚本,或者具有在运行时选择.config文件的代码逻辑。

我不知道Python,所以我不会尝试发布示例代码。 : - )

答案 2 :(得分:0)

this blog post翻译成Python,这应该有效:

import clr
import System.AppDomain
System.AppDomain.CurrentDomain.SetData(“APP_CONFIG_FILE”, r”c:\your\app.config”)

答案 3 :(得分:0)

您始终可以在配置文件中包含其他部分。在您的ipy.exe.config文件中,您可以添加一个include来导入外部配置设置;说myApp.config。

在批处理/命令文件中,您始终可以将特定的.config设置复制到myApp.config中,因此可以根据需要使用不同的配置文件运行。

看一下如何实现这个目标的博客;   http://weblogs.asp.net/pwilson/archive/2003/04/09/5261.aspx

答案 4 :(得分:0)

对于解决方法我所做的是“手动”填充ConfigurationManager静态类的AppSettings集合,因此我创建了一个PY脚本并在IronPython上运行它“导入”,然后这些设置将可用于类库。但是我无法为ConnectionStrings集合赋值:(

我的脚本看起来像这样

import clr
clr.AddReferenceToFileAndPath(r'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll')
from System.Configuration import *
ConfigurationManager.AppSettings["settingA"] = "setting A value here"
ConfigurationManager.AppSettings["settingB"] = "setting B value here"

知道一种将自定义.config文件“加载”到ConfigurationManager类的方法会很好。

答案 5 :(得分:0)

我试图按照上面的答案,但发现它太复杂了。如果您确切地知道App.config文件中需要哪个属性,则可以将其直接放在代码中。例如,我导入的dll需要知道App.Config文件中的AssemblyPath属性。

import clr
import System.Configuration
clr.AddReference("System.Configuration")
from System.Configuration import ConfigurationManager

ConfigurationManager.AppSettings["AssemblyPath"] = 'C:/Program Files (X86)/...

这就是我所需要的,我连接的类库能够看到它运行所需的AssemblyPath属性。