0

How can i get the current directory to which I am in? like the use of

os.getcwd()
Jonathan Lam
  • 1,237
  • 3
  • 20
  • 49

3 Answers3

1

First, I presume you're not asking about a particular subprocess that exists simply to tell you the current working directory and do nothing else (Apducer's answer). If that were the case you could simply as os.getcwd() and forget the subprocess. You clearly already know that. So you must be dealing with some other (arbitrary?) subprocess.

Second, I presume you understand, via dr1fter's answer, that you have control over the working directory in which the subprocess starts. I suspect that's not enough for you.

Rather, I suspect you're thinking that the subprocess might, according to its own internal logic, have changed its working directory sometime since its launch, that you can't predict where it has ended up, and you want to be able to send some sort of signal to the subprocess at an arbitrary time, to interrogate it about where it's currently working. In general, this is only possible if the process has been specifically programmed with the logic that receives such a signal (through whatever route) and issues such a response. I think that's what SuperStew meant by the comment, "isn't that going to depend on the subprocess?"

I say "in general" because there are platform-specific approaches. For example, see:

jez
  • 14,867
  • 5
  • 37
  • 64
0

by default, subprocesses you spawn inherit your PWD. you can however, specify the cwd argument to the subprocess.Popen c'tor to set a different initial PWD.

dr1fter
  • 21
  • 1
  • 2
0

Unix (Linux, MacOS):

import subprocess

arguments = ['pwd']
directory = subprocess.check_output(arguments)

Windows:

import subprocess

arguments = ['cd']
directory = subprocess.check_output(arguments)

If you want to run in both types of OS, you'll have to check the machine OS:

import os
import subprocess

if os.name == 'nt': # Windows
    arguments = ['cd'] 
else: # other (unix)
    arguments = ['pwd']

directory = subprocess.check_output(arguments)
sguridirt
  • 73
  • 1
  • 6