Skip to content Skip to sidebar Skip to footer

How To Include Py File Based On The Command Line Input?

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 wan

Solution 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)

Solution 2:

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()

withopen('file_name.py', 'w') as py_file:
    py_file.write('import ' + module_name)

Solution 3:

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.

Solution 4:

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])

Post a Comment for "How To Include Py File Based On The Command Line Input?"