running subprocess with combined cd and pwd

Question:

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?

Asked By: Florida Man

||

Answers:

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

Answered By: Alberto Garcia

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.

Answered By: Charles Duffy

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

import os.path
os.path.split(os.getcwd())[0]
Answered By: Amos Baker