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.
-
This question might helpgerda die gandalfziege– gerda die gandalfziege2022年02月24日 08:36:42 +00:00Commented Feb 24, 2022 at 8:36
-
What did you try ?ApuCoder– ApuCoder2022年02月24日 09:27:04 +00:00Commented Feb 24, 2022 at 9:27
-
@ApuCoder I have no idea what should I do. I think there should be some way to do that. to run a python script with arguments. But I don't know the trick.Peyman– Peyman2022年02月24日 10:00:19 +00:00Commented Feb 24, 2022 at 10:00
1 Answer 1
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
2 Comments
inference.py file. It is not mine. I only can import and use it in my code.Explore related questions
See similar questions with these tags.