1

I have a script that I want to use with the python shell (interactivity mode, live interpreter, python3 [return]) and the script I want to have added to the live interpreter (python3 -i script.py) has a if __name__ == '__main__': in it. When I load the script the if __name__ runs. I have argsprase in the if __name__ which spits out an error. So, I need to be able to add the script to the live interpreter, but not have certain code in the script run, the code in if __name__.

script.py

#/usr/bin/python3

class myExcellentClass:
    def __init__(var1, var2):
        self.var1 = var1
        self.var2 = var2

    def WhatisVar1(self):
        return self.var1

    def WhatisVar2(self):
        return self.var2

if __name__ == '__main__':
    import argparse

    # setup args parse

    # do some stuff here

I'm thinking there must be a variable that I can add to if __name__ that will test for whether the script is being run with -i or not. For example:

if __name__ == '__main__' && is_interactive == false:
    import argparse

    # setup args parse

    # do some stuff here

If there is a way to call the live interpreter from in side a python3 script, I would just add -i to the script and have this launch the class added to the live interpreter.


I could split out the class into another file. I would like not to do this if possible.

Example:

scriptA.py

#/usr/bin/python3

class myExcellentClass:
    def __init__(var1, var2):
        self.var1 = var1
        self.var2 = var2

    def WhatisVar1(self):
        return self.var1

    def WhatisVar2(self):
        return self.var2

scriptB.py

#/usr/bin/python3

from scriptA import *

if __name__ == '__main__' && is_interactive == false:
    import argparse

    # setup args parse

    # do some stuff here

I usually install the script system wide as a byte-code file for efficiency purposes. (Yes I know that it's not recommend, nor will the pyc work with different versions of python.) As I only need to use the -i for testing and trouble shooting, I would prepare a solution that would allow me to keep everything in one python file.

vy32
  • 28,461
  • 37
  • 122
  • 246
9716278
  • 2,044
  • 2
  • 14
  • 30

2 Answers2

1

Just run python3 and the type from script import *.

a more complete answer here: What does if __name__ == "__main__": do?

soundstripe
  • 1,454
  • 11
  • 19
1

The variable you are looking for actually exists.

from sys import flags
print(flags.interactive)

This prints 1 in interactive mode and zero otherwise.

Wombatz
  • 4,958
  • 1
  • 26
  • 35