When running a project in eclipse the eclipse saves a copy of the .py file inside the workspace defined in project creation. But the file that imported to project can be in other location.
If using os.getcwd() and running the script from the command line, the return value would be the real path of the script file, but when running the script from inside eclipse, the return value would be the path of the workspace, where eclipse saves a copy of the original file.
So the question is, since I run my script during debugging from eclipse, how can I verify that it works before moving to real environment? Is there other way other than getcwd()?
Thanks,
Isaac
os.getcwd() returns the current working directory.
When running a Python program from Eclipse you can specify what the working directory should be on the Arguments tab of the Run Configuration. This will let you override the value from the project folder (or whatever the default might be.)
Related
I am trying to run python code using the jupyter extension in vscode here
I have a workspace open at this location
/Users/user/Documents/
When I try and run the following code in a file called test.py in a child directory, the current working directory is set at the workspace level rather than the file. Is it possible to change a setting to use the cwd of the file, rather than the workspace? I cannot find one in settings.json and the "cwd" in launch.json only seems applicable to debugging.
File location:
/Users/user/Documents/python_code/test.py
#%%
import os
print(os.getcwd())
Expected output:
/Users/user/Documents/python_code/
Actual output:
/Users/user/Documents/
When running the same code through the terminal it prints the expected result, so the issue seems to be related to the jupyter extension
For any specific folder / workspace that you have open in VS Code you can use the notebookFileRoot setting to set a specific absolute path directory to always set the Jupyter working directory to when you start the Interactive Window with that folder open.
Always opening on the file location (without having to set notebookFileRoot to an absolute path per folder) is not supported via the notebookFileRoot setting. The VSCode variables such as ${fileDirname} are specific to task and debug configuration files (launch.json and task.json). We've specifically added code to recognize ${workspaceFolder} for our settings page but we don't recognize other VSCode variables in there.
If you want there is a github item here that has suggested this feature. You can follow that or vote it up if you want this feature added.
https://github.com/Microsoft/vscode-python/issues/4441
Edit 11/5/2019:
We have now made a change to allow the VS Code "Notebook File Root" setting to be set to ${fileDirname}. This setting will now start up Notebook Editor and Interactive Window session relative to the file location that was used to start them.
There is the setting python.dataScience.notebookFileRoot which is, as far as I understand, supposed to achieve the expected behaviour when setting it to ${fileDirname}.
See correspoding source.
However, it does not seem to work in my case. Maybe a bug?
Note that the output of running the script from the terminal depends on you working directory of the terminal!
Saying I create a.py under path/to/somewhere/. And later in the IDE(pycharm), I refactor it to path/to/another_place/.
But when I run a.py later, os.getcwd() show its working directory is still in path/to/somewhere. ( os.listdir('.') also show it is in original place.)
The following picture is what I meet , makeimg.py is originally in learn_function
I am new to python and I don't understand how a file/modoule locate itself.
Am I do something wrong? or it is a bug?
os.getcwd() returns the current working directory, it may/may not be the directory in which the your script exists, its the directory from which the script was run. Most probably in your PyCharm Run/Debug configuration you have set the Working directory to path/to/somewhere .
From run/debug configuration doc page for pycharm -
Working directory - Specify a directory to be used by the running task.
When a default run/debug configuration is created by the keyboard shortcut Ctrl+Shift+F10 , or by choosing Run on the context menu of a script, the working directory is the one that contains the executable script. This directory may differ from the project directory.
Ideally your code should not depend on the current working directory , since you can run a python file from anywhere using absolute path to the python file.
Instead if you want the path in which the script resides, use __file__ to get that path in the script.
Example -
print(__file__)
This should print the script's path (as given in sys.argv[0]).
I can not launch a python script from a .desktop launcher created on Linux Mint 17.1 Cinnamon.
The problem is that the script will be launched in the wrong path - namely the home folder instead of the directory it is placed in. Thereby it can not find other vital files accompanying it in its folder and hence does not work.
To examine that misbehaviour I created a short script to check the folder a python script is executing in:
#!/usr/bin/env python
import subprocess
import time
subprocess.call(["pwd"], shell=True)
time.sleep(7) # to get a chance to read the output
Executing it from its own folder gives the output:
/home/myusername/PythonProjects
I am setting a desktop launcher via Nemo's menu. Now executing the same script yields:
/home/myusername
I do not understand this behaviour. How could I create a working desktop launcher for my python script?
The page describes the format of .desktop files.
You may note the "Path" element, which specifies the working directory for the file to be run in. In your case you would want a desktop file that specified
Path=/home/myusername/PythonProjects
If Nemo doesn't allow you to set the Path element you may need to edit the desktop file by hand. The .desktop files are text files and you can probably find them in /home/myusername/.local/share/applications/
I'm new and I have no idea where the default directory for the open() function is.
For example open('whereisthisdirectory.txt','r')
Can someone advise me? I've tried googling it (and looking on stackoverflow) and even putting a random txt file in so many folders but I still can't figure it out. Since I'm beginning, I want to learn immediately rather than type "c:/directory/whatevevr.txt" every time I want to open a file. Thanks!
Ps my python directory has been installed to C:\Python32 and I'm using 3.2
os.getcwd()
Shows the current working directory, that's what open uses for for relative paths.
You can change it with os.chdir.
If you working on Windows OS first type
import os
then type
os.getcwd()
and it should print the current working directory.
The answer is not python-specific. As with programs written in any other language, the default directory is whatever your operating system considers the current working directory. If you start your program from a command prompt window, the CWD will be whatever directory you were in when you ran the program. If you start it from a Windows menu or desktop icon, the CWD is usually defined alongside the program's path when creating the icon, or else falls back to some directory that Windows uses in the absence of that information.
In any case, your program can query the current working directory by calling os.getcwd().
The default location is the CWD (Current Working Directory), so if you have your Python script in c:\directory and run it from there, if you call open() it will attempt to open the file specified in that location.
First, you must import:
import os
Then to print the current working directory:
os.getcwd()
If you want to change the current working directory:
os.chdir('your_complete_required_path')
create the .txt file in the directory where u have kept .py file(CWD) and run the .py file.
The open() function for file always creates files in the current working directory. The best way to find out your current working directory is to find three lines of small code:
import os
current_working_directory = os.getcwd()
print(current_working_directory)
Run this above code and you will get your current working directory where open() function creates a new file. Good Luck!
If you’re running your script through an interpreter (i.e pycharm, VSCode etc) your Python file will be saved, most likely, in my documents (at least in VSCode, in my personal experience) unless you manually save it to a directory of your choosing before you run it. Once it is saved, the interpreter will then use that as you current directory so any saves your Python script will create will also automatically go there unless you state otherwise.
it depends on how you run it from the terminal
like this, it is going to look in your home directory
C:\Users\name>python path\file.py
and like this, it is going to look next to your file
C:\Users\name>cd path
C:\Users\name\path>python file.py
I've been trying to figure this out for more than 2 days, screening the internet and the tutorial, but yet I don't have solved my problem. I'm a real newb and don't yet really know what I'm doing..
Software I use:
Mac OS X 10.6
Python v3.2.2
Interactive interpreter (IDLE)
Problem:
IDLE's default directory is /Users/ME/Documents/. Files with the extention .py can only be opened when located in this directory. However, I made a folder where I would like to save all the .py files etc that have to do with this software. Currently, IDLE cannot load .py files from the chosen directory by me.
What I did first was I added to IDLE:
import sys.
sys.path.append('Users/Mydir/')
sys.path
However, in an already existing thread from 2010 I read sys.path is for the Interpreter ONLY, and that if I am to change this I need to modify the PYTHONPATH environment variable:
PYTHONPATH="/Me/Documents/mydir:$PYTHONPATH"
export PYTHONPATH
However, I'm confused how to use this and cannot find answers to my following questions:
1) PYTHONPATH (.py?) is already existing on my computer when I installed the program?
If YES, where is it? I cannot find it anywhere.
If NO, I need to create one. But where and what should be the content so that IDLE can load files from a non-default directory? Should it contain only the words in bold?
I hope I made my problem clear.
Cheers
It's not totally clear to me what you mean by load. That could mean Open and Close files in the IDLE editor. Or it could mean being able to use the Python import statement to load existing Python modules from other files. I'll assume the latter, that by load you mean import.
There are two general ways to launch IDLE on Mac OS X. One is from the command line of a terminal session; if you installed Python 3.2 using the python.org installers, by default typing /usr/local/bin/idle3.2 will work. The other way is by launching IDLE.app from /Applications/Python 3.2, i.e. by double-clicking its icon. Because you say the default directory for files is your Documents folder, I'm assuming you are using the second method because IDLE.app sets Documents as its current working directory, which becomes the default directory for *Open*s and *Save*s and is automatically added as the first directory on Python's sys.path, the list of directories that Python uses to search for modules when importing.
If you want to add other directories to sys.path, as you've noted you can use the PYTHONPATH environment variable to do so. The standard way to do this is to add an export PYTHONPATH=... definition to a shell startup script, like .bash_profile. However, if you use IDLE.app, no shell is involved so commands in .bash_profile have no effect.
While there are ways to modify the environment variables for OS X GUI apps, in this case, a simpler solution is to use the other method to invoke IDLE, from the command line of a shell session, using either /usr/local/bin/idle3.2 or, if you've run the Update Shell Profile command in the /Applications/Python 3.2 folder (and opened a new terminal session), just idle3. Then, a PYTHONPATH environment variable you set up will be inherited by that IDLE.
BTW, there is no direct way to modify the initial current working directory of IDLE.app from Documents other than modifying the code in IDLE. If you start IDLE from a command
line, it inherits the current working directory of the shell.
[UPDATE] But rather than fooling around with defining PYTHONPATH, here is another even simpler, and probably better, approach that should work with either IDLE.app or the command line idle. It takes advantage of Python path configuration (.pth) files and user site-package directories. Assuming you are using a standard Python framework build of 3.2 (like from a python.org installer) on Mac OS X, create a path file for the directory you want to permanently add to sys.path. In a terminal session:
mkdir -p ~/Library/Python/3.2/lib/python/site-packages
cd ~/Library/Python/3.2/lib/python/site-packages
cat >my_paths.pth <<EOF
/Users/YOUR_USER_NAME/path/to/your_additional_python_directory_1
/Users/YOUR_USER_NAME/path/to/your_additional_python_directory_2
EOF
Now, whenever you run that Python 3.2 or IDLE under your user name, the directories you have added to the .pth file will automatically be added to sys.path.
BTW, the exact path location of the user site-packages directory for versions of Python earlier than 3.2 or 2.7 may be slightly different. Also, on other Unix-y systems, the default location for the user site-package directory is ~/.local/lib/python3.2/site-packages.
PYTHONPATH is an environment variable (see here and here). I don't have a Mac, but from the threads I have linked to you would type something like
launchctl setenv PYTHONPATH=/Me/Documents/mydir:$PYTHONPATH
on the command line to allow you to run Python scripts from /Me/Documents/mydir. Alternatively, put this line in a file called .bashrc in your home directory (~) and this path will be set each time each time you open a terminal. See here for a short introduction to .bashrc and other .bash* files. Hope that helps.
EDIT See also this question.