cdrom
cdrom

Reputation: 599

Run the interactive mode from a python script

Since I don't know what the interactive python mode really is, my question may be silly. But I still want to ask.

I want a python script that can initialize objects and then run the interactive python mode.

It would behave like this :

$ cat myscript.py
#!/usr/bin/env python3
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-i", action='store_true')
args = parser.parse_args()

if args.i:
    foo = 'bar'
    run_interactive_mode()
$ ./myscript.py -i
>>> foo
'bar'
>>>

Is there a solution for this ?

Upvotes: 2

Views: 342

Answers (2)

Ben
Ben

Reputation: 6358

Yes - use the code module:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-i", action='store_true')
args = parser.parse_args()

def fun():
    print("fun")

if args.i:
    foo = 'bar'
    import code
    code.interact(local={**globals(), **locals()})

And running it:

λ python tmp.py -i
Python 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> foo
'bar'
>>> fun()
fun

Upvotes: 1

Dash
Dash

Reputation: 1299

You're really close, but I think you're overthinking this. Python already has a -i flag. See Python3 Docs. From the docs:

When a script is passed as first argument enter interactive mode after executing the script or the command

In your case, get rid of argparse and create the variables as you like. The interactive terminal will open after the script is done running, and will let you interact with the variables you created during the script

Ex:

#!/usr/bin/env python3
foo = "bar"

$ python -I myscript.py
>>> foo
'bar'
>>>

Upvotes: 1

Related Questions