[英]run python script with an ini file
i'd like to run a python script with different ini files我想用不同的 ini 文件运行一个 python 脚本
I put some variable's in an ini.py and than i would like to run my program.py with this inifile.我将一些变量放在 ini.py 中,然后我想用这个 ini 文件运行我的 program.py。
I tried something like:我试过类似的东西:
in batch-> program.py ini在批处理-> program.py ini
sys.argv[1]
from sys.argv[1] import *
and和
eval('from '+sys.argv[1]+' import *')
but this doesn't work.但这不起作用。
now I wrote:现在我写道:
import sys
f = open('outp.py','w')
f.write("from "+sys.argv[1]+" import *\n")
f.write("print x\n")
with open('program.py', 'r') as content_file:
content = content_file.read()
f.write(content)
f.close()
execfile( "outp.py")
basicly rewriting my program file with an extra import statment.... there is an easier way i hope?!基本上用额外的导入语句重写我的程序文件....我希望有更简单的方法?! (not neccesarely in batch) thx
(不一定是批量的)thx
For parsing INI files, you can use the configparser standard library module in Python. INI文件的解析可以使用Python中的configparser标准库模块。
You can use the __import__
function.您可以使用
__import__
函数。
my_module=__import__('os') #basically the same as `import os as my_module`
Of course, you can't do from blah import *
with this, but many people would argue that you shouldn't use that idiom in production code anyway.当然,你不能用这个
from blah import *
来做,但是很多人会争辩说你不应该在生产代码中使用那个习惯用法。
However, if you just want to set a few variables, you should instead consider a commandline parsing utility, or a config file parser ( configparser
, argparse
and optparse
all come to mind -- all in the standard library) as this will prevent users from running untrusted code.但是,如果您只想设置几个变量,您应该考虑使用命令行解析实用程序或配置文件解析器(
configparser
、 argparse
和optparse
都会浮现在脑海中——都在标准库中),因为这会阻止用户运行不受信任的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.