简体   繁体   English

是否可以将Python脚本中的文本作为可执行命令输出到终端?

[英]Is it possible to output text from a Python script to the terminal as an executable command?

To be specific, I want a Python script that accepts a string from the user and interprets that string as a command in the terminal. 具体来说,我想要一个Python脚本,该脚本接受来自用户的字符串并将该字符串解释为终端中的命令。 In other words, my script should be able to be used as follows: 换句话说,我的脚本应该可以如下使用:

python testScript.py "command -arg1 -arg2 -arg3"

And the output should be as follows: 输出应如下所示:

command -arg1 -arg2 -arg3

which executes the command with 3 arguments: arg1, arg2, and arg3. 它使用3个参数执行命令:arg1,arg2和arg3。

ie,

python testScript.py "ls -lah"

Outputs the permissions of the current directory. 输出当前目录的权限。

Likewise, 同样,

python testScript.py "/testarea ls -lah"

Would output the permissions of the directory, "/testarea" 将输出目录“ / testarea”的权限

Any suggestions or modules? 有什么建议或模块吗?

Running arbitrary user input can be generally considered a Bad Idea©, but if you really want to do it: 运行任意用户输入通常被认为是一个坏主意©,但如果您确实想这样做,则:

#testScript.py
import sys, os

if __name__ == "__main__":
    os.system(" ".join(sys.argv[1:]))

The most robust way of doing this is to use the subprocess module. 最可靠的方法是使用subprocess模块。 Take a look at all the possible options. 看一看所有可能的选项。

https://docs.python.org/2/library/subprocess.html https://docs.python.org/2/library/subprocess.html

Sure... 当然...

The most basic way is to use os: 最基本的方法是使用os:

import os, sys

os.system(sys.argv[1])

If you want do have better control over the calls, have a look at the subprocess module though. 如果您希望更好地控制调用,请查看子流程模块。 With that module you can do the same as above, but do a lot more, like capturing the output of the of the command and use it inside your program 使用该模块,您可以执行与上述相同的操作,但是要做更多的事情,例如捕获命令的输出并在程序中使用它。

This is the best answer I came up with. 这是我想出的最好答案。 I upvoted anyone who said to use the subprocess module or had a good alternative, as well. 我赞成任何说使用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)

This will run the ping www.google.com command for 5 seconds and then timeout. 这将使ping www.google.com命令运行5秒钟,然后超时。 You can add an arbitrary number of arguments to the list when you create command, separated by spaces. 创建命令时,可以在列表中添加任意数量的参数,并用空格分隔。

This is an example of the command ls -lah : 这是命令ls -lah

command = Command("ls -lah")
command.run(timeout=5)

And an example of multiple commands in a single run: 以及一次运行多个命令的示例:

command = Command("echo 'Process started'; sleep 2; echo 'Process finished'")
command.run(timeout=5)

Easy and robust, just how I like it! 简单而强大,正是我所喜欢的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM