running subprocess with combined cd and pwd

54 Views Asked by At

I run subprocess in jupyter to get the core path. I have to go one folder up and then call pwd

Running:

import subprocess
mypath=subprocess.run("(cd .. && pwd)")

leads to a "No such file or directory: '(cd .. && pwd)' error. I guess the cd calls a directory call.

Can you help me out?

3

There are 3 best solutions below

0
Charles Duffy On BEST ANSWER

Frame challenge: subprocess is the wrong tool for this job.

import os.path

mypath = os.path.abspath(os.path.dirname(os.getcwd()))

...is both faster and portable to non-UNIXy operating systems.

0
Alberto Garcia On

for a single shell command (where the arguments are not separated from the command), you need to set shell = True in subprocess.run. Do

subprocess.run("cd .. && pwd", shell = True)

and it will work

0
Amos Baker On

As others have mentioned, no subprocess or shell is required for this.

import os.path
os.path.split(os.getcwd())[0]