问题
My python script has to include other python scripts in the code. And I want the other scripts to be passed as command line arguments. For example: My script is test.py, and I want to include first.py in my code based on the command line input. Command line input
python test.py first.py
In the code I want first.py to be imported as in:
import first
But I can't figure out a way. I tried using optparse and fileInput, but they didn't turn out to be what I had intended.
回答1:
I don't think it is best practice to import module from arguments, but if you really want to do that, could try below code:
import sys
for file_name in sys.argv[1:]:
module_name = file_name.replace('.py', '')
exec('import %s' % module_name)
回答2:
Why doesn't a simple import statement in the original code do the job? Like so:
import first
#
# The rest of the program.
#
Then from the command line, you only need to run
python test.py
As long as test.py and first.py are in the same directory, this approach is effectively "including" first.py in test.py. Please include more information about why you want to pass first.py as a command line argument. It seems to me, since you already know what your program will be doing with first.py, and you have to write your code under the assumption that first.py will be imported anyway, you might as well just do it at the beginning of test.py.
回答3:
python test.py first.py - In this case, test.py is argv[0] and first.py is argv[1]
Add below code in your test.py
from sys import argv
execfile(argv[1])
回答4:
I don't know the best way to answer your question. But here is my solution. Again, this may not be the best solution-
module_name = input()
with open('file_name.py', 'w') as py_file:
py_file.write('import ' + module_name)
来源:https://stackoverflow.com/questions/48001691/how-to-include-py-file-based-on-the-command-line-input