0

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?

Florida Man
  • 2,021
  • 3
  • 25
  • 43
  • BTW, `subprocess.run(['pwd'], cwd='..', stdout=subprocess.PIPE, text=True).stdout.rstrip('\n')` is another way to get where you're going. Still less efficient than using the `os`-module tools, but not as inefficient as spinning up a shell. – Charles Duffy Nov 07 '22 at 18:46

3 Answers3

3

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.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
1

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

Alberto Garcia
  • 324
  • 1
  • 11
0

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

import os.path
os.path.split(os.getcwd())[0]
Amos Baker
  • 769
  • 6
  • 13