Debug python - Error: No main class specified? - python

I installed Intellij 2019 with python plugin. And I opened a directory with python scripts. I'm going to debug script1.py in the directory.
In the "Project Structure" window, I added new Python in the field "Project SDK".
Then, I went to "Run/Debug configurations" folder and clicked the + and added a new Application, I need an command line argument so I filled the field "Program arguments:" with my arguments.
However, at the bottom it shows a read error message: "Error: No main class specified". And I cannot run the python script. What I missed to set up the intellij to run python script?

You need to use Python run configuration instead. Although creating run configurations manually is inconvenient and I would recommend using a context menu or a shortcut so that IDE does it automatically:
See https://www.jetbrains.com/help/pycharm/running-applications.html for more details.

Related

How can I change a PowerShell terminal to a simple one in VScode for Python?

I am new to VScode and want to run Python in it for my college project. I have seen that in VScode all the programmes are executed in Windows PowerShell Terminal(By default). But the problem is that it also shows the file address which is being executed which I don't want. So, please could you give a suggestion which software should be used in the terminal which only executes code and doesn't show any file address. And How can I change it?
VS code supports multiple shells. By default it's powershell (PS >) on windows
Click on "Select Default Profile" to change it (And restart VS code) or you can directly click on any of the available shells (shown in below pic).
About hiding the "file address" - you can always change the shell's corresponding settings file which it reads on load.
Ex: bash shell uses .bashrc settings file. And how to hide file path could be checked here for bash : Show only current directory name (not full path) on bash prompt
Similarly check how it's done for the shell you want
You can try the extension of Code Runner, it will be like this:
Otherwise, you can change the value of "console" in the launch.json file to the internalConsole, then run the python file in the debug mode(F5), it will be like this:
ctrl+shift+ is a Command Used to open terminal in VS code .. You can also Try Extension of python shell or powershell in VSCode ...

In the pycharm IDE how do I run a parametrized function using a script file [duplicate]

I am trying to setup PyCharm to invoke a shell script, instead of python, as the run option. Is this possible? In the default options I only have Python, Python docs, and Python tests. With the professional edition I also have Django and others. However, they all have python as the interpreter in a combobox and they can't be changed as far as I can see.
If you want to see such a feature in PyCharm please vote on IDEA-112256
'Command Line' Run Configuration feature request.
Run/Debug Configurations section of Pycharm's online help lists all supported types of Run/Debug configurations and there's no support for shell scripts indeed.
However, you might be able to add such support by installing a plugin. For example, if you are interested in bash scripts there's BashSupport plugin which adds support for running shell scripts in Run/Debug configuration.
From plugins' home page:
BashSupports can directly run scripts within IntelliJ. You can create
a new run configuration for Bash scripts. Here you can set which
interpreter is used to run it. Whenever a script is executed the
output is logged. If Bash prints out syntax errors then the errorneous
lines are clickable to jump to the location of the error.
For Windows there's CmdSupport plugin which provides an action to run .cmd scripts. It seems it does not support running such scripts as Run/Debug configuration however.
As a workaround you can use Python run/debug configuration, specifying some dummy (empty) Python file to run and use Before launch option specifying External tool and specify path to the script when adding/configuring this external tool. See In IntelliJ IDEA, how can I create a key binding that executes a shell script with the current file as a parameter? for details.
As PyCharm is based on IntelliJ's IDEA platform the question IntelliJ IDEA: Running a shell script as a Run/Debug Configuration is very related.
Speaking of run/debug configurations you might be interested in the plugin Run Configuration as Action which
(...) provides a way to use run configurations as buttons on toolbar.
Or assign shortcuts to execute specific run configuration.
This is really a missing feature that normally should be considered as basic functionality. There are two options
First i tried to create a standard (empty) Python configuration and used the "Before launch"->External tool option, therefore you must create a new external tool definition with Tool Settings:
Program: cmd.exe
Parameters: /C your-batch-file.bat
Working directory $ProjectFileDir$ (In my case $ProjectPath$ was empty)
The annoying thing about this solution is, that the "external tool" standard output is redirected to an extra tab in the console log window which is immediately going into the background when the dummy Python Configuration is executed afterwards.
Second and better is to use python to execute the command. Normally i always use subprocess module but in this case os.system() is the nice and minimal solution. The python run configuration then looks like this
Script: (empty)
Parameters: -c "import os; os.system('your-batch-file')"
Working directory: (select project directory, unfortunately no macros here)
I think the easiest way is to just write a python script that calls the .bat file, and then run that:
from subprocess import Popen
p = Popen("batch.bat", cwd=r"C:\Path\to\batchfolder")
stdout, stderr = p.communicate()
Another hacky solution to this is altering the config/options/jdk.table.xml file in your PyCharm's configuration folder. You simple add another entry in your jdks list:
<jdk version="2">
<name value="Python 3.7 (docker)" />
<type value="Python SDK" />
<version value="Python 3.7.0" />
<homePath value="/path/to/your/shell.sh" />
<roots>
<classPath>
<root type="composite" />
</classPath>
<sourcePath>
<root type="composite" />
</sourcePath>
</roots>
<additional />
</jdk>
After that just select your interpreter for your project and you can use this shell as your interpreter. I used this solution when using interpreter inside docker's image.

Add current file directory to Python interpreter path in PyCharm

PyCharm allows customization of the Python console. By default it adds WORKING_DIR_AND_PYTHON_PATHS to the sys.path:
import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend([WORKING_DIR_AND_PYTHON_PATHS,WORKING_DIR_AND_PYTHON_PATHS + '/..', FILE_DIR])
Is there any variable for the "current file directory" (not current working directory)? This is needed to make relative paths work to other modules in same directory.
This can be done (using option 2 below) but not using the GUI shown in the question (option 1). It must be noticed there are 2 very different ways to launch the Console inside PyCharm.
1. As shown in the question by going to File > Settings > Build, Execution, Deployment > Console > Python Console.
2. Or using the Run/Debug configuration at Run > Edit Configurations.
What the GUI does in the 2 cases is very different
1. In the first case, the IDE simply calls the OS shell with the Python interpreter as first argument and the path to the Console plugin as second argument.
C:\path_to_venv\Scripts\python.exe
"C:\JetBrains\PyCharm 2020.1.1\plugins\python\helpers\pydev\pydevconsole.py"
--mode=client --port=12345
There is one single variable of IDE magic to this (see also the comments in this answer):
Console. Python Console
The WORKING_DIR_AND_PYTHON_PATHS variable is hardcoded in PyCharm. It displays two paths: the project root and the working directory.
This means the IDE does not expose any other "magic variable" that would allow to retrieve the file before or after the Interpreter/Console is being called. Neither Python nor the OS have any way of knowing at this point what file/module you want to use, the only way would be hardcoding the file path as an environment variable (but this doesn't solve anything, because you would have to change the path every time you change file.)
2. The second option, does allow to transparently pass the module/file you currently have opened in the editor when you call the Console.
Basically by creating a run/configuration "template" using a using the "FileDir macro" whenever you run the debugger on any module opened in the editor a "temporary configuration" is created for that module that allows to retrieve the macro value from sys.argv. In this case the file is chosen by the IDE on-the-fly and the macro passes the path along with it.
C:\path_to_venv\Scripts\python.exe
"C:\JetBrains\PyCharm 2020.1.1\plugins\python\helpers\pydev\pydevd.py"
--multiproc --qt-support=auto --client 127.0.0.1 --port 12345
--file C:/path_to_module/teste2.py C:\path_to_module
This 2nd option is how the Console is supposed to be used in PyCharm to get the functionality in the question, as shown in the screenshot.

Pycharm Python Console Won't Run Anything from Script

I am unable to get my pycharm console to access anything from my script. Likewise, when I tell a single line of code to execute in the console, an an error like the one shown in the image is thrown. I am sure that something is not configured correctly, and would appreciate any assistance.
You have a generic console open that doesn't have your script loaded into in automatically. You can tell because the name of the console is "Python Console".
Right click on the code editor window, then at the bottom, click "Run file in Python Console". That will create a new console with the script loaded.
I made that into a key combination (in the Key Bindings in settings) because it's such a common task for me.
You don't need a python console. Just right click on the script name and select run or in pycharm terminal : python script.py
It depends on your scrip

How can I run a .py file with its options in Python console?

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.

Categories

Resources