【问题标题】:Is it possible to output text from a Python script to the terminal as an executable command?是否可以将 Python 脚本中的文本作为可执行命令输出到终端?
【发布时间】:2014-07-09 20:23:57
【问题描述】:

具体来说,我想要一个 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”

有什么建议或模块吗?

【问题讨论】:

    标签: python terminal output


    【解决方案1】:

    运行任意用户输入通常被认为是一个坏主意©,但如果你真的想这样做:

    #testScript.py
    import sys, os
    
    if __name__ == "__main__":
        os.system(" ".join(sys.argv[1:]))
    

    【讨论】:

    • 我同意,但我正在创建的应用程序是一个测试套件,我希望用户(我们的测试人员)能够输入任意数量的参数并将它们存储起来以供随时使用无需记住终端中 200 个不同终端命令的所有参数。
    【解决方案2】:

    最可靠的方法是使用subprocess 模块。看看所有可能的选项。

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

    【讨论】:

    • 在我看到这些 cmets 之前,这是我使用的解决方案(我使用了子进程以及线程来限制每个进程可以执行的时间量)。我也会发布我的最终答案,以便您看到解决此问题的最佳解决方案。
    【解决方案3】:

    当然……

    最基本的方法是使用os:

    import os, sys
    
    os.system(sys.argv[1])
    

    如果您想更好地控制调用,请查看 子流程模块。使用该模块,您可以执行相同的操作 和上面一样,但是做更多的事情,比如捕获 命令并在程序中使用它

    【讨论】:

    • 子流程是它所在的位置。我使用它和线程来限制每个进程可以使用的时间。
    • 我发布了我的答案,但我真的很喜欢你的简单!我只是需要一个更强大的解决方案,并且需要能够在需要时快速终止进程。
    【解决方案4】:

    这是我想出的最佳答案。我赞成任何说要使用 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)
    

    简单而强大,正是我喜欢的方式!

    【讨论】:

      猜你喜欢
      • 2018-01-30
      • 2011-04-13
      • 1970-01-01
      • 2021-10-01
      • 2013-08-13
      • 1970-01-01
      • 2021-05-22
      • 2020-08-20
      • 2016-01-09
      相关资源
      最近更新 更多