-2

Create a module in Python named 'python_1.py' that make the follow:

  1. When import the module from Python console ('import python_1'), return 'Imported'.
  2. When import the module from iPython console ('import python_1'), return 'Imported from iPython'.

  3. When import the module from Command Prompt ('python python_1.py'), return 'Running as script'.

This is what I've done, but i don't know how to know where have been imported:

def python_1(): 
      print 'Imported from iPython'
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

1

You could call the following function:

import sys
def import_check():
    try:
        __IPYTHON__
        return 'Imported from iPython'
    except NameError:
        pass
    a = sys.executable
    m = '\\'
    m = m[0]
    while True:
        b = len(a)
        c = a[(b - 1)]
        if c == m:
            break
        a = a[:(b - 1)]
    if sys.executable == a + 'pythonw.exe':
        return 'Imported'
    else:
        return 'Running as script'

print(import_check())

The first part checks if the __IPYTHON__ variable exists: if so you are running from iPython. The second part checks if you are running from command prompt or from IDLE (Python Console) as when you run from IDLE pythonw.exe is used to run the code whereas if you run it from the command prompt it uses python.exe. What the code does is it simply reverts the Python path to see which exe is running.

Disclaimer: Some of this code was written by @Dylan in this question and another bit was written by @Tom Dunham in this question.

Community
  • 1
  • 1
Joseph Chotard
  • 666
  • 5
  • 15