0

I need to create a module that implements:

  • When imported from a python console (import ) it prints "Imported"

  • When imported from a ipyhton console (import ) it prints "Imported from ipython"

  • When run from a system command line (python .py) it prints "Running as a script"

I think that the last function can be done with

  if __name__ == "__main__":
     print("Running as a script")

And I guess that the first one is with a basic function that prints "Imported from ipython", but how can I make that the module difference between python and ipython? Thank you!!

Saguer
  • 9
  • 2
  • Is it ok to check for the existence of the global `get_ipython`? ...then inside of ifs call there is a string `get_ipython().parent.name` equal to `'ipython'`... – dan_fulea Oct 10 '19 at 15:51

1 Answers1

0

I'm unfamiliar with ipython, however, you may be able to do something like:

import platform

if 'ipython' in platform.sys.version.lower():
     print("Running as a script!")
else:
    print('Imported!')
PygoNode
  • 90
  • 5
  • After importing the `platform` this ipython session gives me for `In [10]: platform.sys.version.lower()` the output `Out[10]: '3.7.4 (default, jul 16 2019, 07:12:58) \n[gcc 9.1.0]'` – dan_fulea Oct 10 '19 at 15:44
  • Ah bummer, the example I saw was using Anaconda and was part of the platform.sys.version output :( -- This may do it for ya https://stackoverflow.com/a/58102605/6120578 – PygoNode Oct 10 '19 at 15:50