How to set cwd in VSCode Ipython? - python

I'm migrating from Spyder to VSCode and would like to use it in a similar way.
One of the major problems I'm facing is to set de cwd to the folder of the file I'm working. There is a lot of question just like mine in the Google, but none of them solved my problem.
Here are my configs:
"code-runner.cwd": "${fileDirname}",
"code-runner.fileDirectoryAsCwd": true,
"terminal.integrated.cwd": "${fileDirname}",
"python.testing.cwd": "${fileDirname}",
"python.terminal.launchArgs": [
"-m",
"IPython"
    ],
"terminal.integrated.defaultProfile.windows": "Command Prompt",
"python.terminal.executeInFileDir": false
What I want to do is to execute my file in IPython with the cwd setted to my file directory, to load some CSVs that are in the file folder, also be able to run some independent lines or enter some code directly in Ipython with all the variables loaded.
I don't want to just RUN the file or DEBUG, because I want to prototype some lines of code right in the IPython console with all the variables loaded.
With my configs, what I usually do is to select all the lines of the script and CTRL + ENTER. This will open a terminal with Ipython but setted to my project folder, not my file folder.
If I open a REPL, I get the same problem: Ipython opened but not set to file folder. Worse I can't use the CTRL + Enter to send some independent lines to Ipython (in this situation CTRL + Enter will cause to open a new terminal)
If I open a terminal by the Terminal menu, the console is setted to my file folder, but without python.
The closest that I got is to open the terminal from Terminal menu, and in the terminal navigate to my python and execute IPython, but then I can't run some independent lines from my code using a shortcut (most precisely like the F9 in Spyder)
My Python is not in Windows path. I'm working with files from a disk E: and my python is on a disk C:.

No Work Reason:
"terminal.integrated.cwd": "${fileDirname}", is the configuration of the default terminal. You can find out the terminal name was powershell or something others. But when you take the command of Run Selection/Line in Python Terminal, the name of the terminal was the explicit name: Python.
Impossible Reason:
Unfortunately, the Python extension seems has not provided the configuration to modify the cwd when you take the command of Run Selection/Line in Python Terminal while you can modify the cwd when you take the command of Run Python File in Terminal. As the IPython has no configuration to modify the cwd too, so it seems has not a suitable method to achieve your aim.
Workaround:
Method1: After you into the REPL mode, modify the cwd like this:
import os
os.chdir('/tmp')
Method2:
Change the configuration: "python.terminal.executeInFileDir": true
Execute the command of Run Python File in Terminal first, in order to change the terminal path.
Execute the command of Run Selection/Line in Python Terminal.
Method3:
Execute the command of Run Selection/Line in Python Terminal.
Exit out and change the path of the terminal.
Run IPython again.

Related

Adapt file path to UNIX- or Windows-style related to VS Code setting "python.terminal.activateEnvironment"

In the .vscode/settings.json of my current workspace, I have:
"python.terminal.activateEnvironment": true
It works upon opening an integrated PowerShell terminal, but both MINGW64 bash and WSL fail like so:
username#hd1pcms0347:/mnt/c/Users/username/Projects/projname$ source c:/Users/username/Projects/projname-venv/Scripts/activate
-bash: c:/Users/username/Projects/projname-venv/Scripts/activate: No such file or directory
Of course, I can manually adapt the file path from
c:/Users/username/Projects/projname-venv/Scripts/activate
to
/c/Users/username/Projects/projname-venv/Scripts/activate
for the MINGW64 bash shell, or
/mnt/c/Users/username/Projects/projname-venv/Scripts/activate
for the WSL shell, to make it work.
Yet, this is suboptimal as it will always require my manual intervention.
How can I achieve that this file path will have automatically either UNIX- or Windows-style depending on the terminal-type I open?
Edit: add screenshot of integrated terminal in VS Code
You should reselect the python interpreter before you create a new terminal using the remote server.

Can't run Python script from Terminal without changing directories even though directory is included in PATH

OS: Mac 10.14.6
Python Version: 3.8.5
New to Python and Bash so apologies if this is a dumb question but I can't find an answer anywhere. The closest I found was this answer on this thread however, I've already executed chmod +x on that file to change the permissions to allow it to be executable and I followed the instructions again and I still couldn't get it to work.
Basically I want to run Python scripts from a specified folder on my desktop (file path ~/Desktop/Python\ Scripts) through Terminal without having to change directories (out of pure laziness).
I added the folder to PATH and can see that it is listed when I run echo $PATH in Terminal. I thought that would do the trick but when I try to run the program with the command python boxprintV2.py as I usually would when I change directories I get python: can't open file 'boxprintV2.py': [Errno 2] No such file or directory
This command works fine if I change the current directory as I have been doing and I can run my program no problem but I would like to run from a new terminal window without having to change directory every time. Permissions on the file have been changed using chmod +x
Shebang from my program is #!/usr/bin/env python3.
If you run the command python <filename>, the Python interpreter will only check the current directory. Therefore, this only works if your working directory is "~/Desktop/Python Scripts", as you have already found out.
Because your script is marked as executable and it includes a shebang at the beginning of the file, you can just execute it directly from the command line by only entering boxprintV2.py. Bash will then search all directories in $PATH for this file and execute it.
Ok, I've found a workaround by creating a shell script following this answer on a different thread.
What I did was open a blank textedit file, go to format and convert it to plain text (or ⇧ + ⌘ + T which toggles rich text/plain text).
From there I typed these commands into the document as follows:
#! /bin/bash
cd ~/Desktop/Python\ Scripts
python boxprintV2.py
When I saved I didn't specify a file extension and unticked the box that said "If no extension is provided, use .txt". I'm not sure if this was necessary but I'm just detailing my exact workflow for anyone else who may have the same (laziness) problem as I do.
I then went back into a blank terminal window and entered:
chmod +x ~/Desktop/Python\ Scripts/boxprintV2to allow the shell script to be executed by all users.
From here I can just open the Python Scripts folder on my desktop, double click on the plain text file which is now a .exe and a new terminal window is opened with my Python script running!
It's literally going to save me tens of seconds of my life. I'm sure I'll waste them anyway.

Cygwin Does Not run .py and .sh File Created in Visual Studio Code

I am running Cygwin terminal in Visual Studio Code (2019), and I tried to run hello.sh and hello.py file, but nothing gets printed out in the terminal. No error message either. I also tried to open a Cygwin terminal outside of Visual Studio, nothing gets printed out either.
However, I created the same files from Pycharm in a venv directory, and copied the files into my Cygwin directory -- it worked.
code in hello.py file:
print("hello world")
code in hello.sh file:
echo hello world
I run these files with the same commands in all of the aforementioned terminals:
./hello.sh
python hello.py
Output when I use hello.py and hello.sh files generated and copied from Pycharm:
hello world
Otherwise nothing goes on when run these two files from Cygwin.
I wonder how this happened and how to generate .py files and .sh that will work directly in VS Studio.
I have seen other threads mentioning a "command not found" error when running .sh files. It is not my case, since no error gets printed out.
Thanks!
According to your description, I tested this process on my computer, and it is recommended that you could refer to the following:
Please ensure that the download and installation of "Cygwin Terminal" is correct.
Before using this terminal to execute a file, please go to the parent folder where the file is located.
1). Execute the "hello.sh" file in the "Cygwin" terminal outside of VSCode:
2). Use the "Cygwin" terminal to execute the "hello.sh" file in VSCode:
3). Use the "Cygwin" terminal in VSCode to execute the "hello.py" file:
In addition, in order to use the "Cygwin" terminal in VSCode, I used the following settings in "settings.json":
"terminal.integrated.shell.windows": "...:/cygwin64/bin/bash.exe",

How to use Anaconda Python to execute a .py file?

I just downloaded and installed Anaconda on my Windows computer. However, I am having trouble executing .py files using the command prompt. How can I get my computer to understand that the python.exe application is in the Anaconda folder so it can execute my .py files?
You should use Anaconda Prompt instead of common Windows command prompt.
Then navigate to your folder with the .py file and run:
python myfile.py
However if you want to use normal command prompt you should put the path with you're python.exe which is usually in
C:\Users\<username>\AppData\Local\Continuum\anaconda3\python.exe
behind this one put your .py file.
Launch JupyterLab from Anaconda
(Perform the following operation with JupyterLab ...)
Click on icon folder in side menu
Start up "Text File"
Rename untitle.txt to untitle.py (The name of the file started up was also changed)
Start up the "terminal" (In windows the power shell starts up)
Execute the command python untitle.py
Right click on a .py file and choose 'open with'
Scroll down through the list of applications and click something like 'use a different program'
Naviage to C:\Users\<username>\AppData\Local\Continuum\anaconda3
click on python.exe and then click on 'ok' or 'open'
Now when you double click on any .py file it will run it through Anaconda's interpreter and therefore run the python code.
I presume if you run it through the command line the same would apply but perhaps someone could correct me?
Just get to the home of jupyter notebook and select "New" then select "Text file".
Then save the text file as file_name.py
Write your code in the file and save the file.
Then open the "Anaconda Prompt" and then type as follows to run your file
python file_name.py
You can do it from the "Anaconda Prompt"
conda run "my_script.py"
I was doing exactly as Martin Bosch suggested, and was getting the following:
(base) C:\>python command.py
python: can't open file 'command.py': [Errno 2] No such file or directory
I solved it this way:
navigate to the exact file location using the "cd" command
for me this was:
(base) C:\>cd my_scripts
this should put you specifically in the file where your .py script is located.
now you should try to input the name of your file.
(base) C:\my_scripts> test_script.py
you may get asked which program to run this with, and simply find python.exe
After doing this process once, I can simply type (in anaconda prompt)
test_script.py
and it runs no problem, even from the top of the file tree (I don't have to be in the exact file, nor do I have to explicitly give the whole file path)
Anaconda should add itself to the PATH variable so you can start any .py file with "python yourpythonfile.py" and it should work from any folder.
Alternatively download pycharm community edition, open your python file there and run it. Make sure to have python.exe added as interpreter in the settings.
If you get the following error:
can't open file 'command.py': [Errno 2] No such file or directory
Then follow this steps to fix it:
Check that you are in the correct directory where the Python file is.
If you are not in the correct directory, then change the current working directory with cd path. For instance: cd F:\COURSE\Files.
Now that you are in the directory where your .py file is, run it with the command python app.py.
Check where is the directory for the ananconda environment directory which is generally
"C:\Users\[UserName]\.conda\envs\[conda environment directory]"
You will see python.exe in that directory.
After that, you need to use the following command to execute your python file (i.e. xx.py) when you are running Anaconda prompt and you will be done:
"C:\Users\[UserName]\.conda\envs\[conda environment directory]\python.exe" xxx.py
BTW, if you have global variable (i.g. variable yyy) that contain directory, you have to define the global variable that contains full path of directory just below the header (the import section) to prevent the "name 'yyy' is not defined" error to occur:
from pathlib import Path # dealing with path issue
yyy = Path("[DriverLettter]:\Full\Path\of\Directory")

How to run a Python project?

I have installed the Enthought Python distribution on my computer, but I don't have any idea how to use it. I have PyLab and IDLE but I want to run .py files by typing the following command:
python fileName.py
I don't know where to write this command: IDLE, PyLab or Python.exe or Windows command prompt. When I do this in IDLE it says:
SyntaxError: invalid syntax
Please help me to figure this out.
Open a command prompt: Press ⊞ Win and R at the same time, then type in cmd and press ↵ Enter
Navigate to the folder where you have the ".py" file (use cd .. to go one folder back or cd folderName to enter folderName)
Then type in python filename.py
Indeed, the command to run a Python file should be run in the command prompt. Python should be in your path variable for it to work flexible.
When the python folder is added to path you can call python everywhere in the command prompt, otherwise just in your python install folder.
The following is from the python website:
Windows has a built-in dialog for changing environment variables
(following guide applies to XP classical view): Right-click the icon
for your machine (usually located on your Desktop and called “My
Computer”) and choose Properties there. Then, open the Advanced tab
and click the Environment Variables button.
In short, your path is:
My Computer ‣ Properties ‣ Advanced ‣ Environment Variables In this
dialog, you can add or modify User and System variables. To change
System variables, you need non-restricted access to your machine (i.e.
Administrator rights).
Another way of adding variables to your environment is using the set
command in a command prompt:
set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
If you do it via My Computer, then look for the line named path in Enviroment Variables. Give that the value of your Python installation folder.
Set PYTHON variable to point to the full path of python.exe.
Then type in command prompt console window:
C:\path_to_folder\ python filename.py

Categories

Resources