2012-02-16 103 views
3

我想知道如果有人可以指導我的例子或幫助我與我的代碼在Linux(centos)上運行命令。基本上,我假設我有一個基本的新服務器,並希望配置它。我想我可以列出我需要運行的命令,它會工作,但我得到的錯誤。這些錯誤與無關緊要(在製作過程中)有關。使用python在linux上運行系統命令?

我想這是因爲(我只是假設在這裏),python只是發送代碼運行,然後發送另一個和另一個,而不是等待每個命令完成運行(腳本失敗後,我檢查並節儉包被下載併成功解壓縮)。

下面的代碼:

#python command list to setup new server 
import commands 
commands_to_run = ['yum -y install pypy autocon automake libtool flex boost-devel gcc-c++ byacc svn openssl-devel make java-1.6.0-openjdk git wget', 'service mysqld start', 
       'wget http://www.quickprepaidcard.com/apache//thrift/0.8.0/thrift-0.8.0.tar.gz', 'tar zxvf thrift-0.8.0.tar.gz', 
       'cd thrift-0.8.0', './configure', 'make', 'make install' ] 


for x in commands_to_run: 
    print commands.getstatusoutput(x) 

如何得到這個工作有什麼建議?如果我的方法是完全錯誤的,那麼讓我知道(我知道我可以使用bash腳本,但我試圖提高我的python技能)。

+0

你看過'os'庫中的'system()'函數嗎? (http://docs.python.org/library/os.html#os.system) – yasouser 2012-02-16 18:02:59

+0

os.system函數不是在Python中運行系統調用的建議方式,並且還沒有一段時間。正如@phihag下面的答案,請查看[subprocess module](http://docs.python.org/library/subprocess.html)。 – michaelfilms 2012-02-16 18:10:20

回答

7

由於commands已被棄用很長一段時間,您應該真的使用subprocess,特別是subprocess.check_output。另外,cd thrift-0.8.0僅影響子流程,而不是您的。您可以撥打os.chdircwd參數傳遞給子功能:

import subprocess, os 
commands_to_run = [['yum', '-y', 'install', 
        'pypy', 'python', 'MySQL-python', 'mysqld', 'mysql-server', 
        'autocon', 'automake', 'libtool', 'flex', 'boost-devel', 
        'gcc-c++', 'perl-ExtUtils-MakeMaker', 'byacc', 'svn', 
        'openssl-devel', 'make', 'java-1.6.0-openjdk', 'git', 'wget'], 
        ['service', 'mysqld', 'start'], 
        ['wget', 'http://www.quickprepaidcard.com/apache//thrift/0.8.0/thrift-0.8.0.tar.gz'], 
        ['tar', 'zxvf', 'thrift-0.8.0.tar.gz']] 
install_commands = [['./configure'], ['make'], ['make', 'install']] 

for x in commands_to_run: 
    print subprocess.check_output(x) 

os.chdir('thrift-0.8.0') 

for cmd in install_commands: 
    print subprocess.check_output(cmd) 

由於CentOS的維護的Python古老的版本,您可能需要使用this backport代替。

請注意,如果您想要將輸出打印出來,您可以使用check_call來調用子進程,因爲子進程默認繼承了stdout,stderr和stdin。

+0

請注意,這可能與您收到的錯誤無關。如果你想讓我們幫助你,*發佈*。 – phihag 2012-02-16 18:08:20

+0

當然,CentOS附帶一個古老的Python,在那裏不起作用... – geoffspear 2012-02-16 18:09:34

+0

我會測試它並讓你知道。我得到的錯誤是文件夾/命令在運行時不存在,但在我去之後檢查它們在那裏。我懷疑這些命令正在運行,而沒有等待前一個命令完成。我會試一試你的代碼並看看結果。 – Lostsoul 2012-02-16 18:13:40