0

I tried out shell scripting because I wanted to automate some Linux commands. But I quickly realized that the code is written very differently from what I was used to and that I don't have the same capabilities and an ocean of tools as I do with high-level programming languages.

So I started researching how to execute commands inside of python. But I ran into a big problem. There are several methods of running commands through python, but from what I know they all execute the commands separately (each time in a new shell).

For example, if I run:

import os

os.system("pwd")

The result would be something like this: /home/username/some/path/

Now if I execute:

os.system("cd ..")
os.system("pwd")

The expected output would be: /home/username/some/

But the reality is that I am still in the same directory (because the commands were executed separately).

I know that there are things like os.chdir() or that I could chain the commands like this cd .. | pwd. But it is not only about changing the directory, and I want to put logic in between those commands while retaining the shell instance.

My question is: Is there any way to do what I want? Is there at least some workaround? Do you know some other language that has these capabilities?

  • `subprocess` with `shell=True` does what you ask (but so would `os.system` if you put the commands in a single string, separated by semicolons). – tripleee Nov 05 '22 at 12:16
  • @tripleee no it won't, any interaction with subrprocess/system commands opens a new shell to execute that command, the only 2 ways to do it in the current script is to either use `os.chdir()` or access the dlls from ctypes ... which is basically rewriting `os.chdir` from scratch in python ... – Ahmed AEK Nov 05 '22 at 12:24
  • `My question is: Is there any way to do what I want? Is there at least some workaround? Do you know some other language that has these capabilities?` you can write your script in bash or CMD or powershell then that would be possible, but no you cannot execute shell commands inside a program ... technically bash/CMD are calling their own `os.chdir` under the hood and it's written in C ... so you are doing **EXACTLY** `os.chdir` no-matter how you name it or what language you write it in. – Ahmed AEK Nov 05 '22 at 12:28
  • Right, so no, there is no way to run a command in your Python process other than by permanently replacing the Python process with that command. The question is slightly unclear about whether that's what the OP wants, or just for multiple commands to run in the same session, which you can do from the shell. – tripleee Nov 05 '22 at 17:22

0 Answers0