Is it possible to launch the Python interpreter at runtime? - python

I would like to know if a Python script could launch the Python interpreter at runtime, making variables accessible from the interpreter.
Let me explain myself. Let's say I have the following script:
x = 20
LaunchInterpreter() #Imaginary way to launch the Interpreter
Now, the interpreter is launched and we can play around with variables.
>>> x #x defined value by the script
20
>>> x*x
400

If you're looking for a dynamic interpreter you can use pdb. It is just a debugger though so should be used only for that purpose but can be used like in the following way;
x = 20
import pdb
pdb.set_trace()
Now you will have an interpreter and you can play around with the variables.
I don't know if this is suitable in your situation but it's the closest thing I can think of with the information provided.
Edit 1:
As stated in the comments by skishore you can also use code.interact(local=locals()) so:
x = 20
import code
code.interact(local=locals())

The -i command line option to Python forces the launching of a command interpreter after a script completes:
python --help
usage: /Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
< ... >
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
so given a file test.py that contains:
x = 7
y = "a banana"
you can launch python with the -i option to do exactly what you'd like to do.
python -i test.py
>>> x
7
>>> y
'a banana'
>>>

Related

Start Python REPL and execute command [duplicate]

I would like to play around in the python interpreter but with a bunch of imports and object setup completed. Right now I'm launching the interpreter on the command line and doing the setup work every time. Is there any way to launch the command line interpreter with all the initialization work done?
Ex:
# Done automatically.
import foo
import baz
l = [1,2,3,4]
# Launch the interpreter.
launch_interpreter()
>> print l
>> [1,2,3,4]
You can create a script with the code you wish to run automatically, then use python -i to run it. For example, create a script (let's call it script.py) with this:
import foo
import baz
l = [1,2,3,4]
Then run the script
$ python -i script.py
>>> print l
[1, 2, 3, 4]
After the script has completed running, python leaves you in an interactive session with the results of the script still around.
If you really want some things done every time you run python, you can set the environment variable PYTHONSTARTUP to a script which will be run every time you start python. See the documentation on the interactive startup file.
I use PYTHONSTARTUP.
My .bash_profile has a path to my home folder .pyrc, which as the import statements in it.
https://docs.python.org/3/using/cmdline.html#envvar-PYTHONSTARTUP
I came across this question when trying to configure a new desk for my research and found that the answers above didn't quite suit my desire: to contain the entire desk configuration within one file (meaning I wouldn't create a separate script.py as suggested by #srgerg).
This is how I ended up achieving my goal:
export PYTHONPATH=$READ_GEN_PATH:$PYTHONPATH
alias prepy="python3 -i -c \"
from naive_short_read_gen import ReadGen
from neblue import neblue\""
In this case neblue is in the CWD (so no path extension is required there), whereas naive_short_read_gen is in an arbitrary directory on my system, which is specified via $READ_GEN_PATH.
You could do this in a single line if necessary: alias prepy=PYTHONPATH=$EXTRA_PATH:$PYTHONPATH python3 -i -c ....
You can use the -s option while starting the command line. The details are given in the documentation here
I think I know what you want to do. You might want to check IPython, because you cannot start the python interpreter without giving the -i option (at least not directly).
This is what I did in my project:
def ipShell():
'''Starts the interactive IPython shell'''
import IPython
from IPython.config.loader import Config
cfg = Config()
cfg.TerminalInteractiveShell.confirm_exit = False
IPython.embed(config=cfg, display_banner=False)
# Then add the following line to start the shell
ipShell()
You need to be careful, though, because the shell will have the namespace of the module that the function ipShell() is defined. If you put the definition in the file you run, then you will be able to access the globals() you want. There could be other workarounds to inject the namespace you want, b̶u̶t̶ ̶y̶o̶u̶ ̶w̶o̶u̶l̶d̶ ̶h̶a̶v̶e̶ ̶t̶o̶ ̶g̶i̶v̶e̶ ̶a̶r̶g̶u̶m̶e̶n̶t̶s̶ ̶t̶o̶ ̶t̶h̶e̶ ̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶i̶n̶ ̶t̶h̶a̶t̶ ̶c̶a̶s̶e̶.
EDIT
The following function defaults to caller's namespace (__main__.__dict__).
def ipShell():
'''Starts the interactive IPython shell
with the namespace __main__.__dict__'''
import IPython
from __main__ import __dict__ as ns
from IPython.config.loader import Config
cfg = Config()
cfg.TerminalInteractiveShell.confirm_exit = False
IPython.embed(config=cfg, user_ns=ns, display_banner=False)
without any extra arguments.

Running Python in command line

I need to write my python commands in command line and get the outputs like
python -c a = 10
python -c print("Hello {}".format(a))
python -c import math
The best approach to your problem would be to write out a .py file and run that.
However, I can imagine that for scripting purposes you may need something like this if you cannot write a file. In that case you could separate your commands by ;, but you are going to be limited to programs without blocks, e.g.:
python3 -c "import math; a = 10; print('Hello {} {}'.format(a, math.sin(a)))"
# prints:
# Hello 10 -0.5440211108893698
but:
python3 -c "import math; a = 10; for i in range(a): print('Hello {} {}'.format(i, math.sin(i)))"
SyntaxError: invalid syntax
but again:
python3 -c "import math; a = 10; [print('Hello {} {}'.format(i, math.sin(i))) for i in range(a)]"
# prints:
# Hello 0 0.0
# Hello 1 0.8414709848078965
# Hello 2 0.9092974268256817
# Hello 3 0.1411200080598672
# Hello 4 -0.7568024953079282
# Hello 5 -0.9589242746631385
# Hello 6 -0.27941549819892586
# Hello 7 0.6569865987187891
# Hello 8 0.9893582466233818
# Hello 9 0.4121184852417566
the last one is of course bad practice and all (a side-effect in a comprehension, etc.) but kind of works.
The easiest way is to use a py file and then invoked it from command line.
Inside the name_file.py put:
a = 10
print("Hello {}".format(a))
import math
In console excute
python name_file.py
See python file
If you need run a few commands. You can run Python interpreter with writing python inside your command line. There will be >>> as a mark that all commands you write will be interpreted by interpreter.
Then you can write the commands. After each command you should press ENTER.
>>> a = 10
>>> print("Hello {}".format(a))
>>> import math
FIRST you have to add the python to your system path
1.right click on THIS PC
2.click on advanced system settings
click on environment variables
click on the path to edit
click on edit
6.search python in START MENU
7.right click on the downloaded package and click on copy full path or if your'e using python 3.6
you can reinstall and check the path from the install menu
8.add the path to the list
NOW YOU CAN DO THIS
TYPE python in the command prompt and voila
you should be able to run on the command prompt

I can't run python file interactivly with terminal

I'm using OSX Mac terminal to run python 2.7.10.
for example:
I have a file called "myfile.py"
so when I want to run it on the terminal it would be like this:
python Desktop/myfile.py
However inside the file I have wrote some functions like
def myFunction(x,y):
return float(x)/y
with this method of running a python script I can not interact with my program and use myFunction to input x and y with different values every time and test myFunction properly.
Thank You,
Try passing -i before the script name
python -i myfile.py
You can learn more about what options are available by running man python.
To quote from the manual:
-i When a script is passed as first argument or the -c option
is used, enter interactive mode after executing the script
or the command. It does not read the $PYTHONSTARTUP file.
This can be useful to inspect global variables or a stack
trace when a script raises an exception.
You can use python -i script.py
This way, script.py is executed and then python enter interactive mode. In interactive mode you can use all functions, classes and variables that was defined in the script.
You can use raw_input() to do that.Your myfile.py code can look like this:
def myFunction(x,y):
return float(x)/y
x = raw_input("Please enter x value: ")
y = raw_input("Please enter y value: ")
print(myFunction(x,y))

run python command line interpreter with imports loaded automatically

I would like to play around in the python interpreter but with a bunch of imports and object setup completed. Right now I'm launching the interpreter on the command line and doing the setup work every time. Is there any way to launch the command line interpreter with all the initialization work done?
Ex:
# Done automatically.
import foo
import baz
l = [1,2,3,4]
# Launch the interpreter.
launch_interpreter()
>> print l
>> [1,2,3,4]
You can create a script with the code you wish to run automatically, then use python -i to run it. For example, create a script (let's call it script.py) with this:
import foo
import baz
l = [1,2,3,4]
Then run the script
$ python -i script.py
>>> print l
[1, 2, 3, 4]
After the script has completed running, python leaves you in an interactive session with the results of the script still around.
If you really want some things done every time you run python, you can set the environment variable PYTHONSTARTUP to a script which will be run every time you start python. See the documentation on the interactive startup file.
I use PYTHONSTARTUP.
My .bash_profile has a path to my home folder .pyrc, which as the import statements in it.
https://docs.python.org/3/using/cmdline.html#envvar-PYTHONSTARTUP
I came across this question when trying to configure a new desk for my research and found that the answers above didn't quite suit my desire: to contain the entire desk configuration within one file (meaning I wouldn't create a separate script.py as suggested by #srgerg).
This is how I ended up achieving my goal:
export PYTHONPATH=$READ_GEN_PATH:$PYTHONPATH
alias prepy="python3 -i -c \"
from naive_short_read_gen import ReadGen
from neblue import neblue\""
In this case neblue is in the CWD (so no path extension is required there), whereas naive_short_read_gen is in an arbitrary directory on my system, which is specified via $READ_GEN_PATH.
You could do this in a single line if necessary: alias prepy=PYTHONPATH=$EXTRA_PATH:$PYTHONPATH python3 -i -c ....
You can use the -s option while starting the command line. The details are given in the documentation here
I think I know what you want to do. You might want to check IPython, because you cannot start the python interpreter without giving the -i option (at least not directly).
This is what I did in my project:
def ipShell():
'''Starts the interactive IPython shell'''
import IPython
from IPython.config.loader import Config
cfg = Config()
cfg.TerminalInteractiveShell.confirm_exit = False
IPython.embed(config=cfg, display_banner=False)
# Then add the following line to start the shell
ipShell()
You need to be careful, though, because the shell will have the namespace of the module that the function ipShell() is defined. If you put the definition in the file you run, then you will be able to access the globals() you want. There could be other workarounds to inject the namespace you want, b̶u̶t̶ ̶y̶o̶u̶ ̶w̶o̶u̶l̶d̶ ̶h̶a̶v̶e̶ ̶t̶o̶ ̶g̶i̶v̶e̶ ̶a̶r̶g̶u̶m̶e̶n̶t̶s̶ ̶t̶o̶ ̶t̶h̶e̶ ̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶i̶n̶ ̶t̶h̶a̶t̶ ̶c̶a̶s̶e̶.
EDIT
The following function defaults to caller's namespace (__main__.__dict__).
def ipShell():
'''Starts the interactive IPython shell
with the namespace __main__.__dict__'''
import IPython
from __main__ import __dict__ as ns
from IPython.config.loader import Config
cfg = Config()
cfg.TerminalInteractiveShell.confirm_exit = False
IPython.embed(config=cfg, user_ns=ns, display_banner=False)
without any extra arguments.

Pipe output of a command to an interactive python session?

What I'd like to do is something like
$echo $PATH | python --remain-interactive "x = raw_input().split(':')"
>>>
>>> print x
['/usr/local/bin', '/usr/bin', '/bin']
I suppose ipython solution would be best. If this isn't achievable, what would be your solution for the situation where I want to process output from various other commands? I've used subprocess before to do it when I was desperate, but it is not ideal.
UPDATE: So this is getting closer to the end result:
echo $PATH > /tmp/stdout.txt; ipython -i -c 'stdout = open("/tmp/stdout.txt").read()'
Now how can we go about bending this into a form
echo $PATH | pyout
where pyout is the "magic solution to all my problems". It could be a shell script that writes the piped output and then runs the ipython. Everything done fails for the same reasons bp says.
In IPython you can do this
x = !echo $$$$PATH
The double escape of $ is a pain though
You could do this I guess
PATH="$PATH"
x = !echo $PATH
x[0].split(":")
The --remain-interactive switch you are looking for is -i. You also can use the -c switch to specify the command to execute, such as __import__("sys").stdin.read().split(":"). So what you would try is: (do not forget about escaping strings!)
echo $PATH | python -i -c x = __import__(\"sys\").stdin.read().split(\":\")
However, this is all that will be displayed:
>>>
So why doesn't it work? Because you are piping. The python intepreter is trying to interactively read commands from the same sys.stdin you are reading arguments from. Since echo is done executing, sys.stdin is closed and no further input can happen.
For the same reason, something like:
echo $PATH > spam
python -i -c x = __import__(\"sys\").stdin.read().split(\":\") < spam
...will fail.
What I would do is:
echo $PATH > spam.bar
python -i my_app.py spam.bar
After all, open("spam.bar") is a file object just like sys.stdin is :)
Due to the Python axiom of "There should be one - and preferably only one - obvious way to do it" I'm reasonably sure that there won't be a better way to interact with other processes than the subprocess module.
It might help if you could say why something like the following "is not ideal":
>>> process = subprocess.Popen(['cmd', '/c', 'echo %PATH%'], stdout=subprocess.PIPE)
>>> print process.communicate()[0].split(';')
(In your specific example you could use os.environ but I realise that's not really what you're asking.)

Categories