In the PyCharm IDE, if I right-click on a function/method with a doctest, sometimes the right-click menu will give me the option: "Run 'Doctest my_function_name'" and sometimes the right-click menu, instead, only gives the option to run the whole file (NOT as a doctest).
What determines when it will give the "run doctest" option and when it will not? Is there a way to force it one way or the other?
Running a module (or the tests in it) in PyCharm is done via a Run Configuration. When you right click a module, PyCharm searches for an existing Run Configuration for that module. If a configuration is found (this can be due to a previous run, or a manual creation of a Configuration), PyCharm will only suggest to run that configuration.
For example, if a configuration of module.py was created to run its doctests, that is the option we'll see when right-clicking module.py. However, if no configuration is found, PyCharm suggests to run the module in different options, depending on the code in the module (run regularly, or run doctests / unittests). Once an option is chosen, PyCharm creates the respective, temporary, Run Configuration, implicitly. From here on, when right clicking the module, you'll only get the configuration that was created for that module.
Important side note: PyCharm saves up to 6 temporary (i.e., Configurations that were created via running a module) Run Configurations- 3 in "Python", i.e., scripts, and 3 in "Python Tests". This means that if you run moduleA.py, moduleB.py, moduleC.py, and then moduleD.py, the temporary Configurations in PyCharm will be moduleB.py, moduleC.py, and moduleD.py. The configuration of moduleA.py will be automatically deleted, unless explicitly saved.
This behaviour can be reproduced as following:
In PyCharm, create a new Python module: "temp"
2.Add the following to the module:
"""
>>> print 3.14
3.14
"""
if __name__ == '__main__':
pass
Right click on the doctest section gives the option to "Run 'Doctests in temp' "
Right click on the main section gives the option to "Run 'temp' "
Choosing anyone of the options, makes the other option disappear in subsequent runs. E.g., choosing to run the module will make the option to run Doctests disappear in subsequent runs, and vice versa.
Going back to the first stage, where it was possible to choose between the two options, is possible by deleting the module's "Run configuration":
Run --> Edit configuration --> Locate the module's current configuration (usually highlighted) --> Click the "Minus" button (top left corner) --> Click "Apply" --> Click OK.
Now we are back at step 3.
(Reproduced in PyCharm 5.0 and 4.5)
To summarize:
If no Run Configuration is found, PyCharm suggests to run the module in any possible way (as a script, doctests, or unittests)
If a Run Configuration is found, PyCharm only suggests that Configuration.
If PyCharm isn't giving you the run option that you want, find the Run Configuration that is preventing it from giving you that option and delete it, or create a new one that will run the file, or method/function, the way you want.
If you don't want to delete configurations, you can also hit the shortcut key for Run | Resume Program (F9 for me) to pop up a complete list of choices
If the above doesn't work for you - make sure that your module is not named doctest; it will cause a conflict and therefore cause the exception.
Related
In PyCharm the run button is in grey, not allowing me to click it to run my code. Is there a simple fix to this?
It is happening because your interpreter isn't configured for your current file. You can run your file easily by right clicking on the tab in which your file is open, and then selecting "run (name of file)". It will automatically configure that file, so you can use the run button after that to run it. Remember that you'll have to do this for every new file that you open.
In order to run things, you should configure few things:
you must select which is the root directory of your code: some people uses directly the root directory (but for test, docs, and eventually also utils (and likes), so also in this case you must select all roots), some people put code in a directory named src or as the package name. In this case you should select it (left click on project panel [the panels with the file and folder list], Mark directory as... menu item).
you should have a default python environment for the project (or some available environments). Go to Settings, Project: ..., Project environment
Then you should configure the run option. Usually it is on left from run button. Click it, and add a run setting: at minimum you should select which file should be run (and the environment, if you didn't yet have a default environment for your project). Later you can configure more suffs, as you like.
There are also other possible reasons, e.g. wrong extension, really bad formatted file, etc., which could hit new programmers. But in such case, we must have more information. Try with a very simple example, e.g. just one line: print("Hello World"), to know that the above 3 steps are correct.
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'm new to unit testing and "im trying to run a pytest on Eclipse. I have searched for hours now and I cant seem to find out what the problem is. Im playing around with the simple examples from the https://pytest.org website. My problem is that pytest just does not run on Eclipse. I can use the command prompt to do the tests, but I would much rather have the results on the console window.
Things I have tried but didnt work;
setting PyUnit test runner to Py.test runner (instead of the default Pydev test runner)
In this case I get the following error message
usage: runfiles.py [options] [file_or_dir] [file_or_dir] [...]
runfiles.py: error: unrecognized arguments: --verbosity inifile:
None rootdir: C:\peepee\pytest\testing
I have set the verbosity to 9 (read somewhere that its the maximum). Didnt make any difference.
Simple code I'm trying to test from the http://pytest.org website
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
Works through the cmd but not on Eclipse.
Please help, as I'm losing time on trying to figure this out. Thanks in advance
It didn't work for you because you left "--verbosity 0" in the parameters text field. I don't know why it's not automatically erased by Eclipse, but when you change the runner you MUST also change the parameters to reflect your preferred test runner (pytest in this case).
Globally for all new configurations:
Window -> Preferences -> PyDev -> PyUnit
Change the test runner to "py.test runner" and clear the parameters (or add the ones you prefer. Make sure they are valid flags for pytest.)
Or, if you prefer, manually for each new run configuration
Create a Python unittest run configuration
Select the class you want to run and the project (if they are not already there)
In the Arguments tab override the pyUnit preferences with a py.test runner (clean up the parameters and add whatever you want to add to pytest flags)
1) open run configurations from run menu
2) right click on python unittest and select new to configure a new configuration
3) select the project and the in the main module, select the module which has your test cases.
4) under arguments tab, check 'override pyunit preferences for this launch'.
5) select Py.test runner from the drop down.
6) type --tb=short and --capture=no (values can be changed depending on user preference)
7) click apply and then click run.
NOTE: If you are using django-configurations for your settings then you MUST set the DJANGO_CONFIGURATION environment variable in the environment variables section of the debugger configuration to whatever you use for your testing runs from the command line.
Found an alternative. Just use the PyCharm IDE which makes pytest very easy to run. Make sure to do the following configuration before running any test.
Click the "Run" tab. Select "Edit configurations"
Add configuration with the "+" symbol
Select "Python test" under that "py.test"
Make sure to fill out the "Target" path and the "working directory"
Happy days. Now you have pytest running with the results displayed on the console window
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.
I'm creating a python test suite (using py.test). I'm coding the tests in Idea and I don't know how to debug a single test.
This is my setting of the debugger. It runs the whole testsuite. So I have to run all the tests before it gets to the one I'm trying to debug.
In your configuration, set:
Target to the relative path of one of your test files, i.e. testsuite/psa/test_psa_integration.py
Keywords to a keyword that identifies the test you are trying to run specifically. If tests are part of a class, Keywords should be something like: TestPsaIntegration and test_psa_integration_example
I don't use IntelliJ, but in PyCharm, you can easily debug tests without going through this tedious process of adding a Run/Debug configuration each time.
To do this with PyCharm, go to:
Preferences (or Settings) > Tools > Python Integrated Tools and set Default test runner to py.test.
Then, back in your file (i.e. test_psa_integration.py), you could just right-click anywhere within the code of a test, and select either Run 'py.test in ...' or Debug 'py.test in...' which will automatically create a new Run/Debug configuration as explained previously.
An alternative is adding --no-cov --capture=no into Additional Arguments. To make this automatic for other test file, add those into the Template part.