1

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.

asked Feb 24, 2022 at 8:31
3
  • This question might help Commented Feb 24, 2022 at 8:36
  • What did you try ? Commented 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. Commented Feb 24, 2022 at 10:00

1 Answer 1

2

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
answered Feb 24, 2022 at 8:38
Sign up to request clarification or add additional context in comments.

2 Comments

I can't change the inference.py file. It is not mine. I only can import and use it in my code.
@peyman seems that module is not supposed to be imported in that case. put down a CR to the codes owner to fix his code.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.