LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   I would like to run a linux command from within a python script (https://www.linuxquestions.org/questions/linux-newbie-8/i-would-like-to-run-a-linux-command-from-within-a-python-script-931792/)

Leroy1990 02-28-2012 02:29 PM

I would like to run a linux command from within a python script
 
Code:

#!usr/bin/python

import os, commands

pattern = raw_input('Enter a command you would like to run: ')
os.system(pattern)

output = commands.getoutput('')

print output

For some reason, I am getting an error when I do sudo python runthisscript.py ...i think it resides in my output = commands. section...any suggestions?

TobiSGD 02-28-2012 03:02 PM

It would actually help to see which error you get, don't you think?
May I also ask why you start a simple script with root privileges?

Leroy1990 02-28-2012 03:08 PM

Quote:

Originally Posted by TobiSGD (Post 4614427)
It would actually help to see which error you get, don't you think?
May I also ask why you start a simple script with root privileges?

Running with sudo is just the way I was taught...My mistake..When running the program the first line says, "Enter a command you would like to run:"
I can type in a command, such as ls or ifconfig, and it works (displays the proper output)...however, the last line (after the output) says sh: Syntax error: ";" unexpected.

Thanks!

TobiSGD 02-28-2012 03:11 PM

Just for clarification: sudo is only needed (and should only be used) when an action needs root privileges. Using it in a different case is simply unnecessary and risky.

Please post the exact output on the screen from the line you start the script to the error message, so that we can get a better understanding of the error.

Leroy1990 02-28-2012 03:17 PM

1 Attachment(s)
Quote:

Originally Posted by Leroy1990 (Post 4614433)
Running with sudo is just the way I was taught...My mistake..When running the program the first line says, "Enter a command you would like to run:"
I can type in a command, such as ls or ifconfig, and it works (displays the proper output)...however, the last line (after the output) says sh: Syntax error: ";" unexpected.

Thanks!

Here is the screen shot...my code is exactly how it appears in my original post.

Dark_Helmet 02-28-2012 03:18 PM

According to online Python documentation for module "commands," you need to supply the actual command in your call to getoutput() (see the examples at the bottom of the page linked).

As an additional note, as the top of the page indicates, the "commands" module has been listed as deprecated since version 2.6. The replacement module "subprocess" was added in version 2.4.

I would suggest using the subprocess module now, even for simple things.

As an example, here's a small script I used a while back demonstrating the subprocess module's Popen call (which is basically what you are trying to do).

The script calculates the rows and columns of the current terminal by invoking the external stty command.

Code:

#!/usr/bin/python

import subprocess
import re

dataProcess = subprocess.Popen( 'stty -a',
                                shell = True,
                                stdout = subprocess.PIPE )
dataProcess.wait()
for outputLine in dataProcess.communicate()[0].split('\n'):
    reMatches = re.search(r"rows ([0-9]+); columns ([0-9]+);",
                          outputLine )
    if( reMatches != None ):
        rows = reMatches.group(1)
        columns = reMatches.group(2)

print "Rows: {0}\nColumns: {1}".format( rows, columns )


Leroy1990 02-28-2012 03:21 PM

Quote:

Originally Posted by Dark_Helmet (Post 4614442)
According to online Python documentation for module "commands," you need to supply the actual command in your call to getoutput() (see the examples at the bottom of the page linked).

As an additional note, as the top of the page indicates, the "commands" module has been listed as deprecated since version 2.6. The replacement module "subprocess" was added in version 2.4.

I would suggest using the subprocess module now, even for simple things.

As an example, here's a small script I used a while back demonstrating the subprocess module's Popen call (which is basically what you are trying to do).

The script calculates the rows and columns of the current terminal by invoking the external stty command.

Code:

#!/usr/bin/python

import subprocess
import re

dataProcess = subprocess.Popen( 'stty -a',
                                shell = True,
                                stdout = subprocess.PIPE )
dataProcess.wait()
for outputLine in dataProcess.communicate()[0].split('\n'):
    reMatches = re.search(r"rows ([0-9]+); columns ([0-9]+);",
                          outputLine )
    if( reMatches != None ):
        rows = reMatches.group(1)
        columns = reMatches.group(2)

print "Rows: {0}\nColumns: {1}".format( rows, columns )


Thanks for the help. However, what if I didn't want to specify the command in the script itself but rather while I am running it? How would I go about restructuring this script to make it work that way.

Dark_Helmet 02-28-2012 03:30 PM

Quote:

Originally Posted by Leroy1990
Thanks for the help. However, what if I didn't want to specify the command in the script itself but rather while I am running it?

You have a variable containing the command as a string, right? (e.g. "pattern")

Python doesn't care whether you give it a literal string or a string stored in a variable.

Here's the script using a command-through-variable approach:
Code:

#!/usr/bin/python

import subprocess
import re

myCommand = 'stty -a'

dataProcess = subprocess.Popen( myCommand,
                                shell = True,
                                stdout = subprocess.PIPE )
dataProcess.wait()
for outputLine in dataProcess.communicate()[0].split('\n'):
    reMatches = re.search(r"rows ([0-9]+); columns ([0-9]+);",
                          outputLine )
    if( reMatches != None ):
        rows = reMatches.group(1)
        columns = reMatches.group(2)

print "Rows: {0}\nColumns: {1}".format( rows, columns )

EDIT:
As a follow-up in case a I misunderstood your question... the lines in green from the code above are output processing statements. You would replace those with whatever processing (or printing) statements your script needs--similar to how you might process the contents of a file line by line.


All times are GMT -5. The time now is 04:20 AM.