简体   繁体   中英

How to load module into python with argv

I want to load oneRunParams.py into my current program but won't know where it is till I run it. I want to have it as an input argument, accessed through argv. I was using:

from oneRunParams import *

I now want to replace this with something that will do the same only with the path to oneRunParams specified.

You can use __import__ :

Here is test.py :

# test.py
import sys

filename = sys.argv[1]
f = __import__(filename[:-3]) # This removes the `.py` extension
f.test()

Here is test2.py :

# test2.py
def test():
    print('hello world')

Running the following the command line:

python test.py test2.py

Gives the following output:

hello world

If you really want to load everything in local scope, you have to do the following:

filename = sys.argv[1]
f = __import__(filename[:-3], globals(), locals(), ['*'])
for k in dir(f):
    locals()[k] = getattr(f, k)

test()
from sys import argv

使用以上声明。

fileName=argv[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM