0

So I have the following directory structure

  • my_dir
    • my_mod
      • __init__.py
      • myfile.py

and in myfile.py

I have a nice command line interface via argparse.

But what if sometimes I want to import a function from this script and use it as if it were a module?

e.g. from myfile import myfunc

when I do this I get an error, mostly because I do some preprocess of the command line arguments which are all none in this case.

from this S.O. post, I know how I can tell if python is called from the command line:

import sys, os
if os.isatty(sys.stdin.fileno()):
    # do things

The inclusions of this line and corresponding replacement of my argument preprocessing does not solve this issue.

What should I do?

4
  • 1
    Your argparsing should only happen if the __name__ variable is equal to "__main__". That's why many python scripts have an if__name__=="__main__" block calling their main() function. Commented Nov 22, 2017 at 15:20
  • Possible duplicate of What does if __name__ == "__main__": do? Commented Nov 22, 2017 at 15:21
  • @ElisByberi not a duplicate (as I do not ask what it does), but that may be the solution, so linking is useful Commented Nov 22, 2017 at 15:30
  • @khelwood ok, I shall try that out. thank you Commented Nov 22, 2017 at 15:30

0

Your Answer

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.