簡體   English   中英

在Python中,執行存儲在字符串中的本地Linux命令的最佳方法是什么?

[英]In Python, what is the best way to execute a local Linux command stored in a string?

在Python中,執行存儲在字符串中的本地Linux命令的最簡單方法是什么,同時捕獲所引發的任何潛在異常並將Linux命令的輸出和任何捕獲的錯誤記錄到公共日志文件中?

String logfile = “/dev/log”
String cmd = “ls”
#try
  #execute cmd sending output to >> logfile
#catch sending caught error to >> logfile 

使用子進程模塊是正確的方法:

import subprocess
logfile = open("/dev/log", "w")
output, error = subprocess.Popen(
                    ["ls"], stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE).communicate()
logfile.write(output)
logfile.close()

EDIT子進程希望命令作為列表運行“ls -l”,你需要這樣做:

output, error = subprocess.Popen(
                    ["ls", "-l"], stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE).communicate()

稍微概括一下。

command = "ls -la"
output, error = subprocess.Popen(
                    command.split(' '), stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE).communicate()

或者你可以這樣做,輸出將直接轉到日志文件,因此在這種情況下輸出變量將為空:

import subprocess
logfile = open("/dev/log", "w")
output, error = subprocess.Popen(
                    ["ls"], stdout=logfile,
                    stderr=subprocess.PIPE).communicate()

subprocess是最好的模塊。

您可以使用不同的方法在單獨的線程中運行腳本,或者在等待每個命令完成的情況下運行腳本。 檢查一些非常有用的文檔:

http://docs.python.org/library/subprocess.html

檢查commands模塊。

    import commands
    f = open('logfile.log', 'w')
    try:
        exe = 'ls'
        content = commands.getoutput(exe)
        f.write(content)
    except Exception, text:
        f.write(text)
    f.close()

指定Exception作為例外下課后except會告訴Python來捕獲所有可能的異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM