Search code examples
pythonsubprocesspython-telegram-bot

Do not change the path with subprocess


Ι need to change the paths using subprocess but it doesn't work

I am using py3.6 - python-telegrambot

it's my code

def sh(bot,update):
  ID = 289444284
  command=update.message.text
  print(command)
  su = subprocess.getstatusoutput(command)
  bot.sendMessage(ID,su[1] )

and also

subprocess.Popen(command, shell=True, stdout=PIPE).communicate()
subprocess.getoutput(command)
os.system(command)

But when I put the cd command back, I'm on the same path and the path does not change

![enter image description here][1]

[1]: screen shot


Solution

  • When you call any of the above (subprocess.* or os.system()) you create a new (child) process if you run cd this way, you change current working directory only for the cd itself, but it does not affect your running python code and any command you execute afterwords. You'd need to use os.chdir() or just hold that information and pass it into newly created children processing with cwd keyword of subprocess.Popen().