1

I have added a batch-file ("addpath.bat") as a system path so that I can run it from any folder using the command "addpath". I need the program to return the the path from where the program is called (not the location of the actual file "addpath.bat").

I have tried: %cd% But that gives me the location of the actual file, which is not what I want.

"addpath.bat"

cd C:\path\to\pythonfile
SET mypath=%cd%
python addpath.py %mypath%

The python-file is only used to print out the output of the batch-file

"addpath.py"

import sys
print(f'\n\nThis is the path: {sys.argv[1]}')

If I am opening the terminal (CMD or PowerShell) on the desktop ("C:\Users\user\Desktop") i expect to have the program return the path:

C:\Users\user\Desktop

  • Well, if you use `cd` to change the current directory, how should any program know what was previously the current directory? The command `cd` as used in the batch file would not work at all if the current directory on starting the batch file is on a different drive than drive C:. The solution is most likely the single line `python "%~dp0addpath.py" "%CD%"`. But there are Python methods to [get current directory](https://stackoverflow.com/questions/3430372/) without passing current directory path via command line parameter to the Python script. – Mofi Sep 24 '19 at 11:28
  • I suggest opening a [command prompt](https://www.howtogeek.com/235101/) window, run `cd /?` and read the output help, run `pushd /?` and read output help, run `popd /?` and read output help, run `call /?` and read output help. – Mofi Sep 24 '19 at 11:31

1 Answers1

0

The problem was, as @Mofi said, that I changed directory before trying to get the path. The solution is to define mypath before changing directory and then using it in the python-file

"addpath.bat"

SET mypath=%CD%
cd C:\path\to\pythonfile
python addpath.py %mypath%

"addpath.py"

import sys
print(f'\n\nThis is the path: {sys.argv[1]}')