0

When I need to execute a script-B from script-A, I am using subprocess call to start that script-B in a specific directory-B, but it executes as though it is in the directory-A of the script-A which is calling it with subprocess.

Script-B creates files. The files that it creates should be created in directory-B, but they are generated in directory-A instead.

Below: PATH is directory-B, self is script-B.

I am trying

PATH = some_directory
# Get current script name

self = os.path.basename(__file__)
    
# Copy old-self to desired directory.
os.popen(f"copy {self} {PATH}\\{self}")

# Open new-self in selected dir
subprocess.call([f"{PATH}\{self}"])
Tiwaz Tyr
  • 13
  • 3
  • (1) `shutil.copy(file,PATH)` will do the copy. No external needed. (2) `cwd = os.getcwd()` / `os.chdir(PATH)` / `subprocess...` / `os.chdir(cwd)`. (3) Just do `subprocess.call([self])`. No string work needed. – Tim Roberts Dec 05 '22 at 22:02
  • Your answer was very broad, but I figured it out after some time. I changed some stuff about how the script-b is initialized, code is altered but it is overall the same as my original. I got it to work using: subprocess.call(["f"{PATH}\\script.bat""],cwd=PATH) – Tiwaz Tyr Dec 05 '22 at 23:01
  • That shouldn't work. If you are in the `PATH` directory, then there is not going to be a file called `"PATH\script.bat"`. It would be `"./script.bat"`. – Tim Roberts Dec 05 '22 at 23:25
  • The code snippet doesn't use envi PATH variable; as in this case PATH = input() and the input is data received from a socket connection, although I didn't explicitly state that, I simply used dummy value of some_directory -- due that the question was only concerning subprocess executing an application within a separate directory, and not executing as if in the directory of the application calling subprocess. Perhaps, anyway it is malpractice to use PATH in this way and I should use something else like DesiredDir or path, instead. Thank you, though, for directing me toward the solution. – Tiwaz Tyr Dec 06 '22 at 16:44
  • I know this. What I'm saying is, if you create a directory called "aaa", then create a file called "aaa/script.bat", then do "chdir aaa", the command "aaa\script.bat" will fail -- the file is not found. – Tim Roberts Dec 06 '22 at 19:32

0 Answers0