jean
jean

Reputation: 1013

Python function that calls bash commands

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

Upvotes: 0

Views: 180

Answers (1)

Kasravnd
Kasravnd

Reputation: 107357

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

subprocess.Popen(['ls','-l'])

Upvotes: 1

Related Questions