Reputation: 4179
I know there is a similar question from near 8 years ago but that didn't help. I will have this error when I import the python script with the accepted answer too.
I want to import another python script and use it. My python files name is inference.py
import inference
This python file is written for being used by the command line and it gets two arguments. So if you want to use it in the windows command line you should use it like this
python inference.py arg1 arg2
The problem is when I import it into my python code I will get this error. And it seems it is because I didn't pass the two arguments to it.
inference_filepath = str(sys.argv[1])
IndexError: list index out of range
I want to get help with how can I use import and use this python script In my python code?
P.S: I can't change the inference.py
file, It is not mine. I only can import and use it in my code.
Upvotes: 1
Views: 764
Reputation: 365
You seem to have code that is run regardless of how the file is called.
The code you wish to always run can be left as is, but the code that only should be run if the file is called from commandline should like this:
# Code that always must be run
print("File is called in some context")
if __name__ == "__main__":
# Write your code here to be executed if the file is called from CMD line
import sys
inference_filepath = str(sys.argc[1])
else:
# If you have extra imports or other setup that must be done at import
# include the code for that here
Upvotes: 2