0

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

1 Answer 1

1

You need to put your command and its option in a list :

subprocess.Popen(['ls','-l'])
Sign up to request clarification or add additional context in comments.

5 Comments

yes that works, but would you happen to know why (['cd', '/']) gives me a error of: "No such file or directory" ?
you need to use subprocess.Popen(['cd','/'],shell=True) for that ! but for change directory a better way is using os.chdir
subprocess.Popen(['ls','-l']) works fine for me. No need for shell=True here.
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'].
yes you are right ,so as i dont knew actually what you want to do with cd / so i just give a common proposition !;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.