1

How do i run bash commands from python while the session is maintained. For example if I pwd, then cd .., then pwd, it SHOULD move to a directory level one level lower than the current directory . I dont want to run all these commands as a single command with | or &. I want to run them on individual lines.

vmwgeek
  • 87
  • 2
  • 11
  • Why do you want Python in the mix? Why not just use a shell script? Or why do you want Bash in the mix? Why not just use a Python script? It sounds like you're making your life hard for the sheer fun of making it hard. To achieve what you want, you'd have to have Bash reading commands from its standard input and your Python script would have to write commands to the pipe connected to the Bash input, and you have to specify what you want to happen to the Bash output and error output. Not trivial, but probably sort of doable, if there's a good reason to actually do it, which is debatable. – Jonathan Leffler Jun 18 '18 at 00:04
  • So basically I want to run my commands to build a product and run tests on it using python. This needs me to call commands like 'make' and all. And I need to do this in Python. – vmwgeek Jun 18 '18 at 17:01

1 Answers1

1

In general, processes can't modify the environment of their parent process, or any other existing process. So you can't do this easily in the way you're describing, unless you deliberately save the environment from the child process somehow (e.g. end all your bash commands by redirecting env to a file, prefixing each entry in the file with export, and source that file at that at the start of every subsequent command...).

Alternatives:

  • Add all of your inter-dependent bash commands to a single bash script and run the bash script from python, rather than running bash commands in python one by one.
  • Use os.chdir and other methods to change the python process environment variables as needed before running each bash command.
Ollin Boer Bohan
  • 2,296
  • 1
  • 8
  • 12