Add current file directory to Python interpreter path in PyCharm - python

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.

Related

what is PyCharm Run Edit configuration equivalent in VS code?

In the PyCharm to debug any Python file, following configuration can be added.
Go to Run -> Edit Configurations and click on +
enter code hereSelect Python
Give some name
Provide Script: ->
Provide Script parameters: -> <>
Provide Environment variables: -> <>
Provide Python interpreter: -> <>
Provide Working directory: -> <>
So I wanted to know how to add equivalent configuration on VS code launch.json
So far I have got to know below parameters in VS code and remainig parameters I am trying to understand.
Provide Script parameters:
Provide Python interpreter:
Thanks a lot in advance.
As mentioned in the comments, what you said comes from the docs. You can edit your launch.json file to set it:
Provide Script parameters
args
Specifies arguments to pass to the Python program. Each element of the argument string that's separated by a space should be contained within quotes, for example:
"args": ["--quiet", "--norepeat", "--port", "1593"],
Provide Environment variables
env
Sets optional environment variables for the debugger process beyond system environment variables, which the debugger always inherits. The values for these variables must be entered as strings.
Provide Python interpreter
Python
The full path that points to the Python interpreter to be used for debugging.
If not specified, this setting defaults to the interpreter selected for your workspace, which is equivalent to using the value ${command:python.interpreterPath}. To use a different interpreter, specify its path instead in the python property of a debug configuration.
Provide Working directory
cwd
Specifies the current working directory for the debugger, which is the base folder for any relative paths used in code. If omitted, defaults to ${workspaceFolder} (the folder open in VS Code).

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

Debug python - Error: No main class specified?

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.

Call a Python script (in a directory in the PATH) from command line with Windows

With Linux, if you create a file mycommand with +x permission in a folder which is in the PATH, containing a Python shebang #!..., then calling mycommand from command line works, no matter the current directory.
How to have the equivalent on Windows? i.e. I have a folder D:\myscripts\ which is in the PATH, containing a few personal scripts like mycommand.py.
How to make that calling mycommand or maybe just python mycommand from commandline will work, no matter the current working directory?
TL;DR: I'd like to avoid to have to do
python D:\myscripts\command.py
each time I want to call every-day-use personal scripts from D:\myscripts\
Note: .py files are associated with my text editor (i.e. when double-clicking on a .py file, it is opened with the text editor) and I want to keep this.
Solution 1
I finally did like this:
put D:\myscripts\ in the PATH (with setx, see How to update system PATH variable permanently from cmd?)
create a batch file: D:\myscripts\mycommand.bat containing:
#python d:\myscripts\mycommand.py
That's it!
Solution 2
Here is a solution from various comments from #ErykSun:
Open the system environment variables editor and ensure that "D:\myscripts" is in PATH (do not use quotes) and ".PY" is in PATHEXT (do not use quotes).
Create a test file D:\myscripts\test_command.py with the line import sys; print(sys.executable); print(sys.argv).
In a new command prompt that was opened from Explorer (to get the updated environment variables), run the test script from another directory as test_command spam eggs. If it runs with the expected Python installation and the command-line arguments "spam" and "eggs" are correctly passed, then you're done.
When double-clicking and running at the command prompt, the shell executes the default action for the filetype. If the filetype doesn't explicitly define a default action, the shell uses the "open" action, and if that's not defined it uses the filetype's first defined action, whatever that is. Python configures an "open" action for its "Python.File" filetype and additional context-menu (right-click) actions for editing with IDLE.
There are other directions you can go with this. You can use shell links. Add ".LNK" to PATHEXT and remove ".PY". Then for each script that you want to run, create a shell link (.LNK shortcut file) in D:\myscripts that runs the script explicitly as "path\to\python.exe" "\path\to\script". Leave the working directory field empty, so that it inherits the working directory of the parent process. For example, create D:\myscripts\test_command.lnk to run D:\myscripts\test_command.py.
In this case, you would run the script as test_command, which will find and execute "test_command.lnk". To get the default Sublime edit action, you would explicitly run test_command.py with the ".PY" extension.
Solution 3
Create an .exe file in c:\python37\scripts\ with this method: How to create a .exe similar to pip.exe, jupyter.exe, etc. from C:\Python37\Scripts?
but it's more complicated since it requires a package, etc.

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