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?

SumNeuron
  • 4,850
  • 5
  • 39
  • 107
  • 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. – khelwood Nov 22 '17 at 15:20
  • Possible duplicate of [What does if \_\_name\_\_ == "\_\_main\_\_": do?](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) – Elis Byberi Nov 22 '17 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 – SumNeuron Nov 22 '17 at 15:30
  • @khelwood ok, I shall try that out. thank you – SumNeuron Nov 22 '17 at 15:30

0 Answers0