Florida Man
Florida Man

Reputation: 2157

running subprocess with combined cd and pwd

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?

Upvotes: 0

Views: 93

Answers (3)

Amos Baker
Amos Baker

Reputation: 839

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

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

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295679

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.

Upvotes: 3

Alberto Garcia
Alberto Garcia

Reputation: 339

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

Upvotes: 1

Related Questions