具体来说,我想要一个Python脚本,该脚本接受来自用户的字符串并将该字符串解释为终端中的命令。换句话说,我的脚本应该可以按以下方式使用:
python testScript.py "command -arg1 -arg2 -arg3"
输出应如下所示:
command -arg1 -arg2 -arg3
它使用3个参数执行命令:arg1,arg2和arg3。
IE,
python testScript.py "ls -lah"
输出当前目录的权限。
同样地,
python testScript.py "/testarea ls -lah"
将输出目录“ / testarea”的权限
有什么建议或模块吗?
这是我想出的最好答案。我赞成说使用该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)
简单而强大,正是我所喜欢的!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句