2

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 ?

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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'
>>>

1 Comment

Yes, thank you. It can be useful, but in my case, I need to have more control over when the interactive mode is executed and what to do when it is executed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.