Vladimir Mihailenco
Vladimir Mihailenco

Reputation: 3382

/bin/sh - non interactive usage from Python

I am invoking cmd from Python like this:

subpocess.Popen(['coffee'], shell=True)

which I belive is translated to:

/bin/sh -c "coffee"

From docs I have read that in non-interactive mode files like /etc/profile, /etc/bash.bashrc are not read and default $PATH is used (init $PATH). Am I right? Is there the only way to add coffee to the $PATH is to copy it to /usr/local/bin?

Upvotes: 1

Views: 700

Answers (2)

DigitalRoss
DigitalRoss

Reputation: 146171

Historically, none of the startup files are read for shells invoked as non-interactive commands, since presumably the environment is already set up.

Python, shells, and in fact almost everything will pass the existing environment or at least the PATH environment variable through to the child shell and so, in a way, you have already executed .profile or a bash extension. (Because it was run when the user logged in and other processes inherited the modified PATH.)

Options you have:

  • specify a path for all system users in /etc/profile
  • require appropriate PATH settings from the user (you inherit them)
  • run subprocess utilities with full pathnames
  • put all commands in directories already on the PATH

Upvotes: 2

Fred Foo
Fred Foo

Reputation: 363767

No, the shell will inherit the PATH from the Python interpreter, i.e. it will be os.getenv('PATH'). Also, you can set the path within the command:

subprocess.Popen(['PATH=/where/ever/bin:$PATH coffee'], shell=True)

though I'd really advise you to either use the full path to coffee, or set the PATH before executing your Python program.

Upvotes: 2

Related Questions