Ok, im trying to understand how to use subprocess.
I've made a little problem for practice and i just can't do it. what i want to do is: ping google then do a "cd" command
so basically i want to see the ping command return values and then the directory where my program is
This maybe to much info, so you can just jump to the last code section. ______________________________Jump______________________________________
I have tried many versions of a code. I managed to half do it with "run" command but that returns a "CompletedProcess" and i can't use that.
So first try was pinging google
result=subprocess.run('ping google.com', stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))
this worked fine, then i susbtituted "'ping google.com'" for "'cd', shell=True" And finnaly substituted cd for dir, and decode could not decode the output (why?).
Ok so after that i tried:
result=subprocess.run(['cd ..'], shell=True, stdout=subprocess.PIPE)
result.run(['cd'], shell=True, stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))
And got:
AttributeError: 'CompletedProcess' object has no attribute 'run'
as expected. So this lead me to Popen, so i started all over with it:
result=subprocess.Popen('ping google.com', stdout=subprocess.PIPE)
print(result.communicate()[0].decode('utf-8'))
_____________________Stop Jump____________________________
Now i want to send the "cd" after the ping, i have tried multiple ways of doing this, such as:
result=subprocess.Popen('ping google.com',shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
a='cd\n'
result.communicate(a.encode('utf-8'))
print(result.communicate()[0].decode('utf-8'))
this prints just the ping. I tried removing "[0].decode('utf-8')" - no cd output
I expected to see the ping result, then the cd output, what can i do?
Ultimately i want to run several commands that depend on the previous output.
Bonus question: I want to apply a program using Popen to a raspbian terminal, it's the same correct?
Edit: my question is not about cd, its about running multiple commands in the same terminal, cd could be just pinging a different ip