简体   繁体   中英

How to get current directory with subprocess?

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

os.getcwd()

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:

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM