[英]Is it possible to output text from a Python script to the terminal as an executable command?
具體來說,我想要一個Python腳本,該腳本接受來自用戶的字符串並將該字符串解釋為終端中的命令。 換句話說,我的腳本應該可以如下使用:
python testScript.py "command -arg1 -arg2 -arg3"
輸出應如下所示:
command -arg1 -arg2 -arg3
它使用3個參數執行命令:arg1,arg2和arg3。
即
python testScript.py "ls -lah"
輸出當前目錄的權限。
同樣,
python testScript.py "/testarea ls -lah"
將輸出目錄“ / testarea”的權限
有什么建議或模塊嗎?
運行任意用戶輸入通常被認為是一個壞主意©,但如果您確實想這樣做,則:
#testScript.py
import sys, os
if __name__ == "__main__":
os.system(" ".join(sys.argv[1:]))
最可靠的方法是使用subprocess
模塊。 看一看所有可能的選項。
當然...
最基本的方法是使用os:
import os, sys
os.system(sys.argv[1])
如果您希望更好地控制調用,請查看子流程模塊。 使用該模塊,您可以執行與上述相同的操作,但是要做更多的事情,例如捕獲命令的輸出並在程序中使用它。
這是我想出的最好答案。 我贊成任何說使用subprocess
模塊或有不錯選擇的人。
import subprocess, threading
class Command(object):
def __init__(self, cmd):
self.cmd = cmd
self.process = None
def run(self, timeout):
def target():
print 'Thread started'
self.process = subprocess.Popen(self.cmd, shell=True)
self.process.communicate()
print 'Thread finished'
thread = threading.Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
print 'Terminating process'
self.process.terminate()
thread.join()
print self.process.returncode
#This will run one command for 5 seconds:
command = Command("ping www.google.com")
command.run(timeout=5)
這將使ping www.google.com
命令運行5秒鍾,然后超時。 創建命令時,可以在列表中添加任意數量的參數,並用空格分隔。
這是命令ls -lah
:
command = Command("ls -lah")
command.run(timeout=5)
以及一次運行多個命令的示例:
command = Command("echo 'Process started'; sleep 2; echo 'Process finished'")
command.run(timeout=5)
簡單而強大,正是我所喜歡的!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.