I am trying to make a Python function that will take a bash command (cmd) as an argument, and then execute that command.
But I am having some issues...
This is my program:
import subprocess
def main():
runCommand("ls")
runCommand("ls -l")
runCommand("cd /")
runCommand("ls -l")
def runCommand(cmd):
subprocess.Popen(cmd)
It works for commands like "ls" or "who" but when it gets longer such as "ls -l" or "cd /" it gives me an error.
Traceback (most recent call last):
File "<string>", line 1, in ?
File "test.py", line 8, in main
runCommand("ls -l")
File "test.py", line 14, in runCommand
subprocess.Popen(cmd)
File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__
errread, errwrite)
File "/usr/lib64/python2.4/subprocess.py", line 996, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
asked Oct 11, 2014 at 16:57
jean
1,0131 gold badge12 silver badges25 bronze badges
1 Answer 1
You need to put your command and its option in a list :
subprocess.Popen(['ls','-l'])
answered Oct 11, 2014 at 17:01
Kasravnd
108k19 gold badges167 silver badges195 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
jean
yes that works, but would you happen to know why (['cd', '/']) gives me a error of: "No such file or directory" ?
Kasravnd
you need to use
subprocess.Popen(['cd','/'],shell=True) for that ! but for change directory a better way is using os.chdiruser1277476
subprocess.Popen(['ls','-l']) works fine for me. No need for shell=True here.
user1277476
Each subprocess.Popen will start a distinct shell that doesn't live very long. So when you "cd /", and the shell exits, your cd / is lost in the next shell. So if you need to cd around, you'd probably better use something like shell=True and ['cd / && ls -l'].
Kasravnd
yes you are right ,so as i dont knew actually what you want to do with
cd / so i just give a common proposition !;)default