python 动态加载代码,Python动态导入脚本,需要将其__name__ ==" __ main __"要调用的代码...

While importing a python script from another script I want the script code that is classically protected by

if __name__ == "__main__":

....

....

to be run, how can I get that code run?

What I am trying to do is from a python script, dynamically change a module then import an existing script which should see the changes made and run its __main__ code like it was directly invoked by python?

I need to execute the 2nd python script in the same namespace as the 1st python script and pass the 2nd script command line parameters. execfile() suggested below might work but that doesn't take any command line parameters.

I would rather not edit the 2nd script (external code) as I want the 1st script to be a wrapper around it.

解决方案

If you can edit the file being imported, one option is to follow the basic principle of putting important code inside of functions.

# Your script.

import foo

foo.main()

# The file being imported.

def main():

print "running foo.main()"

if __name__ == "__main__":

main()

If you can't edit the code being imported, execfile does provide a mechanism for passing arguments to the imported code, but this approach would make me nervous. Use with caution.

# Your script.

import sys

import foo

bar = 999

sys.argv = ['blah', 'fubb']

execfile( 'foo.py', globals() )

# The file being exec'd.

if __name__ == "__main__":

print bar

print sys.argv

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值