When ran from a terminal, sys.argv[0] is the path of current script, but in python interactive that variable points to "/some/path/ipykernel_launcher.py" which is a temporary file.
How do I get the path of current script (which I am editing in vscode)? I need this information because whenever I create a file, I automatically log which script created it. For that, I overload the open() function to automatically log the creation. But when file is created from a python interactive session, I am missing such information.
import os
print(os.getcwd())
I think that's what you want. It prints the current working directory.
The answer that works for me, obtained from How do I get the path and name of the file that is currently executing? is this:
os.path.realpath(__file__)
I tried all other suggestions, but didn't work.
Related
I am trying to use python subprocess to call an exe. The application usually takes the parameter file from the same directory as exe. However, as the python file is not located at the same directory as exe, the exe cannot find the parameter file when called by subprocess.run. Hence I specified the cwd when calling subprocess.run like below:
subprocess.run([cwd_exe, "--cal-cn-bv", cwd_cif, "Cs1"], cwd=r'd:\Study\softBV_mix\GitHub\projects\Coord\bin', capture_output=True)
However the subprocess still cannot find the dat file in
d:\Study\softBV_mix\GitHub\projects\Coord\bin
The error message appears as
CompletedProcess(args=['d:\Study\softBV_mix\GitHub\projects\Coord\bin/softBV0405.exe',
'--cal-cn-bv',
'd:\Study\softBV_mix\GitHub\projects\Coord\test/CsCl.cif',
'Cs1'], returncode=0, stdout=b'Warning: unable to find
d:\Study\softBV_mix\GitHub\projects\Coord\database_unitary.dat
where the database_unitary.dat is supposed to be in .../coord/bin/. The application works well if I call it from powershell or command prompt.
No one has answered my question but I kind of found the workaround myself though I am sure if I identify the root cause correctly.
In the end I imported os and make sure cwd is the recognised absolute addresss
import os
cwd = os.path.abspath("../bin")
This worked out.
So the expression
r'd:\Study\softBV_mix\GitHub\projects\Coord\bin'
make cause the issue. Hope some PRO can further clarify this.
Every time I try to do an action such as running a program in the VScode Terminal (also happens in PyCharm) I have to enter in the full pathname instead of just the file name. For example, instead of just doing python3 test.py to run a program, I have to enter in python3 /Users/syedrishad/Desktop/Code/test.py.
Now, this is annoying and all but it doesn't bother me too much. What does bother me is when my program is trying to pull/ open files from somewhere else. If I wanted an image call Apple.jpeg, instead of just typing in Apple.jpeg, I'd have to go and find the full pathname for it. If I were to upload a piece of code doing this to someplace like GitHub, the person who'd want to test this code out for themselves will have to go in and replace each pathname with just the file name or it won't work on their computer. This problem has been going on for a while, and I sadly haven't found a solution to this. I would appreciate any help I get. I'm also on a Mac if that makes a difference.
You could use os and sys that gives you the full path to the folder of the python file.
Sys gives you the path and os gives you the possibility to merge it with the file name.
import sys, os
print(sys.path[0]) # that is the path to the directory of the python file
print(sys.path[0]+'/name.txt') #full path to the file
print(os.path.join(sys.path[0],'name.txt')) # os.path.join takes two parameters and merges them as one path using / but the line above is also fine
In VS Code, its internal terminal is in the currently opened project folder by default. Therefore, when you use the command "python file_name.py" to run the file, the terminal cannot find the file that exists in the inner folder.
Therefore, in addition to using the file path, we can also add related settings to help it find the file.
Run: When using the run button to execute the file, we can add the following settings in "settings.json", it will automatically enter the parent folder of the executed file.
"python.terminal.executeInFileDir": true,
"When executing a file in the terminal, whether to use execute in the file's directory, instead of the current open folder."
debug: For debugging code, we need to add the following settings in "launch.json":
"cwd": "${fileDirname}",
I currently have a Python scrip that runs through all Excel files in the current directory and generates a PDF report.
It works fine now but I don't want the users to be anywhere near frozen Python scripts. I created an MSI with cxFreeze which puts the EXE and scripts in the Program Files directory.
What I would like to be able to do is create a shortcut to this executable and pass the directory the shortcut was run from to the Python program so that can be set as the working directory. This would allow the user to move the shortcut to any folder of Excel files and generate a report there.
Does Windows send the location of a opened shortcut to the executable and is there a way to access it from Python?
When you launch a shortcut, Windows changes the working directory to the directory specified in the shortcut, in the Start in field. At this point, Windows has no memory of where the shortcut was stored.
You could change the Start in field to point to the directory that the shortcut is in. But you'd have to do that for every single shortcut, and never make a mistake.
The better approach is to use a script, rather than a shortcut. Place your actual Python script (which we'll call doit.py for sake of example) somewhere in your PYTHONPATH. Then create a single-line Python script that imports it:
import doit
Save it (but don't name it doit.py) and copy it to each directory from which you want to be able to invoke the main script. In doit.py you can use os.getcwd() to find out what directory you're being invoked from.
You could also do it with a batch file. This is a little more flexible in that you can specify the exact name of the script and which Python interpreter should be used, and don't need to store the script in a directory in PYTHONPATH. Also, you don't need to worry about the file's name clashing with the name of a Python module. Simply put this line in a file:
C:\path\to\your\python.exe C:\path\to\your\script.py
Save it as (e.g.) doit.bat and copy it into the directories from which you want to invoke it. As before, your Python script can call os.getcwd() to get the directory. Or you can write it so your Python script accepts it as the first argument, and write your batch file like:
C:\path\to\your\python.exe C:\path\to\your\script.py %cd%
Another thing you can do with the batch file approach is add a pause command to the end so that the user is asked to press a key after the script runs, giving them the opportunity to read any output generated by the script. You could even make this conditional so that it only happens if an error occurs (which requires returning a proper exit code from the script). I'll leave that as an exercise. :-)
Is there a problem with modifying the script to take the directory to process as a command line argument?
You could then configure the different shortcuts to pass in the appropriate directory.
Type the following into a batch file (i.e. script.bat):
python \absolute\path\to\your\script.py %~dp0
pause
Then add these imports at the top of your python file script.py (if not already included):
import os
import sys
And add this to the bottom of the python file (or combine it with a similar statement):
if __name__ == "__main__":
# set current working directory:
if len(sys.argv) > 1:
os.chdir(sys.argv[1])
main()
replace main() with whatever function you want to call or code you want to run.
The following is how I came to my answer:
I tried using kindall's answer and had the following issues:
The first suggestion of storing the script somewhere in PYTHONPATH could not be applied to my situation because my script will be used on a server and needs to be independent of the client computer's python environment (besides having the required pip installations).
I tried calling my python script from a Windows Batch File which could be moved to a different location. Instead of the batch file's location being used as the current working directory, it was C:\Windows.
I tried passing %cd% as an argument to my python script, then setting that to be my CWD. This still resulted in a CWD of C:\Windows.
After reviewing the comments, I tried Eryk Sun's suggestion of instead passing %~dp0 as an argument to the python script. This resulted in the CWD being correctly set to the batch file's location.
I hope this helps others facing similar difficulties.
I am using sqlite3 and python for a new website I am creating. The problem is, the "files_storage.db" file I am trying to create will not appear in any Windows 10 Folder Window, PyCharm's Directory View, nor will it appear via the command line interface.
The catch to this is, if I execute my python script multiple times, I get an error that states the database file already exists... So this file is somewhere, I guess it is a game of cat and mouse to find it.
I have ran into this problem before, but I have ALWAYS been able to find the file via the command line. Usually, I wouldn't both yall with such a question but, this is really irking me and I am going to run into serious issues when it comes time to put this baby on a server. :(
thanks in advance, and here's some screenshots I suppose.
You are using a relative file path.
Relative paths are converted to absolute ones by something like os.path.join(os.getcwd(), <relative path>). So they depend on the current working directory of the process.
Try to open it with an absolute path (starting with drive letter) to avoid any ambiguities.
If you use just a filename without a path, the file will be saved in whatever the current working directory of the Python interpreter is.
To see where the current working directory is, add the following code to the beginning of your program:
import os
print(os.getcwd())
You should then see the working directory in the output.
There is a setting for the current working directory in your IDE somewhere. See e.g. the answers to this question.
You can also do something like:
import os
path = os.path.expanduser("~") + '/Documents'
print(path)
This will allow you to access the directories for the current user. For me, this prints:
'/Users/thomasweeks/Documents'
I'm trying to make a Python script run another program from its own path.
I've got the execution of the other program working using os.system, but the program will crash because it cannot find its resources (wrong path, I assume). I tried adding the folder harboring the executable to the path, but that didn't help.
You can change the current directory of your script with os.chdir(). You can also set environment variables with os.environ
Use the subprocess module, and use the cwd argument to set the child's working directory.
These two methods from the os library will do the work:os.chdir and os.system.
path = "C://Program Files//Microsoft SQL Server//Client
SDK//ODBC//130//Tools//Binn//" #make sure to use forward slash
program = "bcp.exe"
os.chdir(path)
os.system(program)