python中調用命令列命令,python調用命令列

來源:互聯網
上載者:User

python中調用命令列命令,python調用命令列

http://blog.csdn.net/pipisorry/article/details/46972171

在Python/wxPython環境下,執行外部命令或者說在Python程式中啟動另一個程式的方法

1、os.system(command)

os.system()函數用來運行shell命令。此命令可以方便的調用或執行其他指令碼和命令

  • #開啟指定的檔案  
  • >>>os.system('notepad *.txt') 

  • 2、wx.Execute(command, syn=wx.EXEC_ASYNC, callback=None)

    若置syn為wx.EXEC_ASYNC則wx.Excute函數立即返回,若syn=wx.EXEC_SYNC則等待調用的程式結束後再返回。

    callback是一個wx.Process變數,如果callback不為None且syn=wx.EXEC_ASYNC,則程式結束後將調用wx.Process.OnTerminate()函數。

    os.system()和wx.Execute()都利用系統的shell,執行時會出現shell視窗。如在Windows下會彈出控制台視窗,不美觀。下面的兩種方法則沒有這個缺點。

    3、import subprocess

    subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)

    subprocess.call (["cmd""arg1""arg2"],shell=True)

    Note:

    1. 參數args可以是字串或者序列類型(如:list,元組),用於指定進程的可執行檔及其參數。

    2. 如果command(args)不是一個可執行檔,shell=True不可省

    3. Popen.wait()可以得到命令的返回值

    舉個栗子

    if subprocess.Popen('dir /b %s' % filename, shell=True).wait() == 0
    如果filename字串中有空格,則會出現錯誤:File Not Found錯誤

    可以通過下面["cmd""arg1""arg2"]兩種方式

    if subprocess.Popen(["dir", "/b", filename], shell=True).wait() == 0

    if subprocess.call(["dir", "/b", filename], shell=True) == 0

    [Python中subprocess學習]

    4、webbrowser.open(url)

    前面三個方法只能用於執行程式和開啟檔案,不能處理URL,開啟URL地址可用webbrowser模組提供的功能。

    調用系統預設瀏覽器開啟URL地址,如 webbrowser.open('http://www.jb51.net'),也可以利用
    webbrowser.open('h:\python.zip')來執行程式。這樣可以不必區分是檔案名稱還是URL,不知道在Linux下是否可行。
    以上在Windows2000,Python2.4a1,wxPython 2.5.1運行。
    [python調用shell的方法]

    from:http://blog.csdn.net/pipisorry/article/details/46972171

    ref:python中執行linux命令(調用linux命令)


    著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.