I'm using visual studio code with standard python extension, my issue is that when I run the code the python interpreter instantly closes right after and I only see the output which means that if I create some data structure I have to create it every single time. Is it possible to leave the console open after running the code and maybe running multiple files in the same python interpreter instance?
I used to use spyder which is entirely doing what you want (probably like PyCharm)...
Then I briefly tried VS Code, and it is quite easy to make it behave that way too.
First make sure you have an integrated terminal open (or do Ctrl+`, or View > Integrated Terminal), then in that terminal launch ipython.
Now, when you use the commands from Don Jayamanne's Python extension (Ctrl+Shift+P to open commands palette):
"Run Python File in terminal"
"Run select/line in Terminal"
It will run the line inside the ipython console directly. So running the entire file will call python module.py inside ipython, and thus fails.
So to make this work simply create settings to map which command is executed when "Run select/line in terminal":
Open Language specific settings (Shift+Ctrl+P, search "Configure Language specific Settings...")
Pick up Python
Now I would suggest to make change only in your workspace settings (top-right tab) to keep default behaviour in other cases
so add in WORKSPACE SETTINGS:
(keep in mind it is just a simple/stupid workaround)
{
"python.pythonPath": "run"
}
Now when runing whole file, it will use ipython function run within the ipython terminal that we launched, thus keeping all your workspace variables.
Also, if you run some line of code with "Run Select/Line in Terminal", the ipython session of that terminal keep all variables.
This allows live debugging, without actually going in the debug mode.
When you run a program, it runs until it ends. Then it closes. If you want it to stay live longer, you can make a program which does not stop until told so, e.g.
while True:
something = raw_input('Write something: ')
print('You wrote: %s' % something)
if something == 'bye':
print 'bye.'
break
This will run until user writes "bye".
I'm quite late to this conversation, but a workaround I use is to put a pass statement at the end of my file, then add a breakpoint to it. I then run it in the debugger and can access all of the variables etc.
This allows most of the functionality that I used to use in the PyCharm python terminal, such as exploring data structures, checking out methods, etc. Just remember that, if you want to make a multi-line statement (eg. for a loop), you need to use Shift-Enter to go to the next line otherwise it'll try to evaluate it immediately.
Related
I often use the python breakpoint() command as a way of debugging code or for changing the values of variable on-the-fly. This works great when I launch a python script from the (windows) console, as breakpoint() lets me type commands in that console.
My question is how do I do achieve something similar when running a python script launched some other way? For example, when I package my code into an .exe with PyInstaller (with the no-console option to keep it tidy) and launch the .exe, breakpoint() does nothing at all. I know one way to remove this problem is to compile the .exe without the no-console option, but I'd rather have it there as it just keeps everything clean. A similar problem also arises when running a python script via a os.execl() call in another.
Is there someway of making the code launch its own console whenever breakpoint() is called, and having that console control the debugging commands? I suspect that this is possible through manipulating the PYTHONBREAKPOINT variable, but I don't know how, or where to start looking.
I am trying to run this GitHub project in python, but I could only run it using the Terminal of Pycharm IDE.
According to the guide from the GitHub repository, I removed the $ sign from the beginning of $ python train.py RGCN PPI and could run it there. What does $ mean here and how can I run a file like this in Python Console (for example after >>> sign)?
The '$' isn't part of Python's syntax, it's a visual cue in the documentation representing the command prompt.
To answer the question from the title of this post, I'll provide some
instructions first on how to load scripts into the Python console.
However, for your specific case, you don't need this. Scroll down to
the part about debugging in PyCharm.
There's two ways you can get your script into the console. One is to simply load it using the right version of the two lines I give right below, or you can load it as a module - even if it wasn't intended to be one.
In general, to execute a script in the Python shell on Python 2 you can do
>>> execfile(r"<path to script here>")
On Python 3 it's more verbose:
>>> exec(open(r"<path to script here>").read())
The effect this has is as if you cut-n-pasted the script into the console. The console's global scope will get all the functions, classes, and variables that are leftmost indented in the file. Also it might not run your if __name__ == '__main__': block. But you could hack that.
If you want the vars/classes/etc to be put in another scope than your console's global scope, then there are two additional parameters to the above commands. The first one is a dictionary for the globals , and one for the locals. You can get away with only supplying the globals parameter - it's just an ordinary dictionary object you need.
If the file you want to load is a module, you could import it as you would any other module by appending its home folder to the Python module search path, and using the import directive. You can load your script this way even if it wasn't intended to be module.
>>> import sys
>>> sys.path.append(r'/Users/todd/projects/mymodule_folder')
>>> import mymodule
If you make modifications to it and want to reload it:
>>> import importlib
>>> importlib.reload(mymodule)
Loading your script as a module avoids polluting your console's global scope. After it loads, just prefix the names of your script's functions and variables with the module name. The module name will be the name of the file without the .py extension.
If the script requires command line options, you could just hard code values for those into the script and disable lines of code that try and get values from the CLI. If it gets complicated, consider running it in an IDE as described in the next section.
So the above is how you can run your python scripts in whatever Python REPL console you want.
BUT loading your scripts into the Python console may not be at all
required for your purposes. You wanted to debug some scripts (train.py,
test.py) from this project:
https://github.com/microsoft/tf-gnn-samples).
Debugging Command Line Script With PyCharm
In many cases, a Python script is written to run from the OS shell and take command line options from the user. These kinds of script could be loaded into the Python console, but most require some minor hacks to run. However, if all you want to do is debug such a script, you don't need to muck with the console.
PyCharm supports running these as is (as does Eclipse and other IDEs) like any other script. It's just a matter of creating a run/debug configuration for the project. I just installed PyCharm and gave it a try in order to record the details. Easy task.
Just open the project in PyCharm, and above the editor pane, on the toolbar, there's a menu option for Edit Configurations. Click that to open the Run/Debug Configurations dialog and click the + to add a configuration. A small dialog will appear with predefined templates - select Python as your template and accept.
Then in the main dialog, fill in Script path: with the path to train.py (or another script), then click the checkbox, [x] Emulate terminal in output console. Also, you can add command line options in the Parameters: text box (I put in the text: mymodel mytask just to satisfy the script's need for two parameters). Click OK at the bottom to accept the configuration and shut the dialog.
Now you should see a green bug icon on the toolbar.Set a breakpoint in the __main__ block of the script and click the debug icon to start debugging the script. That should do it!
Debugging Python Command Line Script with PDB
PDB - the Python Debugger can be run without an IDE. This is another way to debug a script of any sort. If it requires command line parameters, provide them from the OS shell when you start the debugger:
$ pdb myscript.py mymodel mytask
That's really all there is to starting a debug session. PDB requires some knowledge of its text based commands. After starting a session, you can get a listing of code near the current line of execution by entering l. Enter help to see a listing of the commands.
To step one line of execution, enter 's' for step, or enter 'step'. To set a breakpoint, enter break <line-number>, or set a breakpoint on an expression. A reference on the commands available can be found here: https://docs.python.org/2/library/pdb.html . There are also plenty of versions of pdb cheatsheets available online - just google "pdb cheatsheet" and select one.
I am writing Python scripts in Pycharm with IPython installed. So I can use Python Console in Pycharm to type Python commands and check the immediate output of the codes. However, when I run a script file after pressing 'Run' button (Shift+F10), all the variables and functions are not visible to the Python Console. This is, however, the feature of Spyder, another popular Python IDE. So here is my question: how can I configure Pycharm so that running a Python script file is visible for Python Console? Thanks
You could also run the part of your code you want to test/check in the console by selecting it and then right clicking and clicking on "Execute Selection in Console Alt-Shift-E". That's what I use sometimes when the debugger is not helpful. After running the code (you can also just "run" functions or classes) the console knows the functions and you can use the same features that Spyder has. However, be aware that when you change the code you need to run it in the console once to update the console definitions!
You can not. But you can use pdb (which will break code execution where you need it and you will be able to do the same things, as in the Python Console).
And, which is better and more powerful, you can use PyCharm's debugger. It represents all available variables in tree-like structures and is really handy.
I'm using visual studio code with DonJayamanne python extension. It's working fine but I want to have an interactive session just like the one in Matlab, where after code execution every definition and computational result remains and accessible in the console.
For example after running this code:
a = 1
the python session is terminated and I cannot type in the console something like:
b = a + 1
print(b)
I'm aware that the python session can stay alive with a "-i" flag. But this simply doesn't work.
Also every time I run a code file, a new python process is spawned. Is there a way to run consecutive runs in just one console? Again like Matlab?
This sounds really essential and trivial to me. Am I missing something big here that I can't find a solution for this?
I'm the author of the extension.
There are two options:
Use the integrated terminal window (I guess you already knew this)
Launch the terminal window and type in python.
Every statement executed in the REPL is within the same session.
Next version will add support for Jupyter.
Please have a look here for some samples of what is yet to come:
#303
Screen samples and more
I added the following lines into user setting file, then it works.
Select some lines of python code, then right-click and select Run selected code in python terminal
Solution 1: Will start iPython terminal
"terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe",
"terminal.integrated.shellArgs.windows": ["/K ipython"],
Solution 2: Will start a terminal like "python -i"
"python.terminal.launchArgs": ["-i"],
The following line will solve your problem.
"python.terminal.launchArgs": ["-c","\"from IPython import embed; embed()\""]
I have set F2 prompt key with map <f2> :w<cr>:! D:\Python34\python %<cr>,when i open an python file in vim and press F2,the python file will be executed .For a simple example,
here is my python file and opened in gvim .
Now i can't input other python lines ,only thing i can do is to see the result and hit any key to close this window.
What i want is :
when i press F2, (the python file was opened in gvim) ,the python console pop up,and all the files in the python file were copied into the python console automatically,and i can go no to input some lines such as Obj().hello in the python console or go on to edit in gvim ,i am a lazy man ,the gvim and python console all opened waiting to serve me , can i write a vim scripts to achieve the target?
The command :!D:\Python34\python -i % works fine ,i got the ouput
There is still a problem remain,
1)when command :!D:\Python34\python -i % works ,the gvim window will be frozen , i can't drag my mouse to see codes in vim.
2)there is no any python codes in the python console wiondow
So if the program is full of many lines ,and i can't remember the previous content ,worse still, the gvim window frozen ,how can i get the codes?
Avoid blocking
To make the call asynchonous (to avoid that GVIM is blocked during the Python session), use the Windows-specific :!start command:
nnoremap <f2> :w<cr>:!start D:\Python34\python -i %<cr>
List teh codez
I don't know whether it is possible to list the passed source code from the interactive Python debugger. But you can print the file contents before starting it:
nnoremap <f2> :w<cr>:!start cmd /c type % && D:\Python34\python -i %<cr>
Additional tips
You should use :noremap; it makes the mapping immune to remapping and recursion.
As your mapping only works correctly from normal mode, use :nnoremap (or extend it to support visual-mode selections, too).
Maybe Vim plugin Conque will solve your problem:
Installation instrucions are here https://code.google.com/p/conque/
To use just type :ConqueTermVSplit python -i test.py (VSplit is for vertical split - you may use horizontal)
There is no blocking of your window with python code - you may escape interactive mode and switch to your window with Ctrl+W twice
You could approach the problem from the Python angle (2.7).
Keep the file where it is (or save it with some unique name to a temporary directory) and have python load the file directly.
Go to that location in your shell and run python interactively (or have vim spin off an interpreter for you)
Import your file import demo
Experiment with what you have implemented demo.SomeModule().meth()
Make some changes in vim
Reload your python module reload(demo)
Experiment with your code again demo.SomeModule().differentMeth()
You can also have vim create a file with shortcut functions for loading/reloading the file you are working on. When vim kicks off the interpreter, you can have it set this file to the PYTHONSTARTUP environment variable, which is a file the interpreter will automatically load when it starts up. For example, you could have a function called r() to automatically reload the file you are working on.
It's also worth mentioning that reloading modules can be a little weird. If you instantiate some modules then reload the file, only new modules will use the new code; the old modules will run with the old code.