LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie
User Name
Password
Linux - Newbie This Linux forum is for members that are new to Linux.
Just starting out and have a question? If it is not in the man pages or the how-to's this is the place!

Notices


Reply
  Search this Thread
Old 02-28-2012, 03:29 PM   #1
Leroy1990
LQ Newbie
 
Registered: Feb 2012
Posts: 8

Rep: Reputation: Disabled
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?

Last edited by Leroy1990; 02-28-2012 at 03:33 PM.
 
Old 02-28-2012, 04:02 PM   #2
TobiSGD
Moderator
 
Registered: Dec 2009
Location: Germany
Distribution: Whatever fits the task best
Posts: 17,130
Blog Entries: 2

Rep: Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825
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?
 
1 members found this post helpful.
Old 02-28-2012, 04:08 PM   #3
Leroy1990
LQ Newbie
 
Registered: Feb 2012
Posts: 8

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by TobiSGD View Post
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!
 
Old 02-28-2012, 04:11 PM   #4
TobiSGD
Moderator
 
Registered: Dec 2009
Location: Germany
Distribution: Whatever fits the task best
Posts: 17,130
Blog Entries: 2

Rep: Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825Reputation: 4825
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.
 
1 members found this post helpful.
Old 02-28-2012, 04:17 PM   #5
Leroy1990
LQ Newbie
 
Registered: Feb 2012
Posts: 8

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by Leroy1990 View Post
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.
Attached Thumbnails
Click image for larger version

Name:	screenshot.png
Views:	35
Size:	18.8 KB
ID:	9153  
 
Old 02-28-2012, 04:18 PM   #6
Dark_Helmet
Senior Member
 
Registered: Jan 2003
Posts: 2,786

Rep: Reputation: 370Reputation: 370Reputation: 370Reputation: 370
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 )
 
1 members found this post helpful.
Old 02-28-2012, 04:21 PM   #7
Leroy1990
LQ Newbie
 
Registered: Feb 2012
Posts: 8

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by Dark_Helmet View Post
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.
 
Old 02-28-2012, 04:30 PM   #8
Dark_Helmet
Senior Member
 
Registered: Jan 2003
Posts: 2,786

Rep: Reputation: 370Reputation: 370Reputation: 370Reputation: 370
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.

Last edited by Dark_Helmet; 02-28-2012 at 04:37 PM.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
how to run python script from c? rabbit2345 Programming 3 01-31-2010 06:42 PM
Run external program from python script MTK358 Programming 1 12-21-2009 07:26 PM
How do I make python programs run without entering the command python? trist007 Programming 5 03-22-2009 09:21 PM
run a bash script using python. deathalele Programming 3 09-13-2008 09:07 PM
how to Run python script on .bash_profile warnetgm Linux - Newbie 32 09-08-2005 06:56 AM


All times are GMT -5. The time now is 06:28 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration