【问题标题】:How can I execute an os/shell command from python [duplicate]如何从 python 执行 os/shell 命令 [重复]
【发布时间】:2016-03-08 05:48:03
【问题描述】:

比如说在终端我做了cd Desktop,你应该知道它会将你移动到那个目录,但是我如何在 python 中做到这一点,但使用带有raw_input("") 的桌面来选择我的命令?

【问题讨论】:

  • 您是在问如何在 Python 中通过 raw_input 执行 shell/cmd 命令吗?
  • 查克洛根是正确的,谢谢你了解我的问题
  • Chuck Logan 我检查了一下,我看到没有 raw_input 的迹象
  • 你使用的是python 2还是python 3?来自 python 2 的 raw_input 现在在 python 3 中是 input

标签: python


【解决方案1】:

以下代码使用 raw_input 读取您的命令,并使用 os.system() 执行它

import os

if __name__ == '__main__':
    while True:
        exec_cmd = raw_input("enter your command:")
        os.system(exec_cmd)

最好的问候, 亚龙

【讨论】:

  • 使用代码时 cd 不起作用
  • 请参阅以下有关“cd”的问答stackoverflow.com/questions/35843054/…
  • 当我打开文件并执行 cd /home/pi/Desktop/asf1/dos 时没有任何反应
  • 如此处所述:stackoverflow.com/questions/35843054/… - 执行此代码时,使用“cd /home” - 在 python 运行时更改目录。 python 进程结束后,您会收到带有原始当前目录的原始 shell。
  • 对此很抱歉,但我怎样才能让它不结束呢?
【解决方案2】:

要使用您的具体示例,您需要执行以下操作:

import os
if __name__ == "__main__":
    directory = raw_input("Please enter absolute path: ")
    old_dir = os.getcwd() #in case you need your old directory
    os.chdir(directory)

我以前在我编写的一些目录维护功能中使用过这种技术,它可以工作。如果你想更普遍地运行 shell 命令,你会像这样:

import subprocess
if __name__ == "__main__":
    command_list = raw_input("").split(" ")
    ret = subprocess(command_list)
    #from here you can check ret if you need to

但要小心这种方法。这里的系统不知道它是否传递了一个有效的命令,所以它很可能会失败并错过异常。更好的版本可能如下所示:

import subprocess
if __name__ == "__main__":
    command_kb = {
        "cd": True,
        "ls": True
        #etc etc
    }
    command_list = raw_input("").split(" ")
    command = command_list[0]
    if command in command_kb:
        #do some stuff here to the input depending on the
        #function being called
        pass
    else:
        print "Command not supported"
        return -1
    ret = subprocess(command_list)
    #from here you can check ret if you need to

此方法表示支持的命令列表。然后,您可以根据需要操作 args 列表以验证它是有效的命令。例如,您可以检查您要访问的目录cd 是否存在,如果不存在则向用户返回错误。或者您可以检查路径名是否有效,但仅在通过绝对路径连接时才有效。

【讨论】:

    【解决方案3】:

    也许你可以这样做:

    >>> import subprocess
    >>> input = raw_input("") 
    >>> suprocess.call(input.split()) # for detail usage, search subprocess
    

    详情可搜索subprocess模块

    【讨论】:

    • 这将在input = "ls -l" 的情况下引发错误,如subprocess 文档中所示。您需要通过space 字符来split 输入字符串,以便为subprocess.call() 提供可以使用的东西(列表)。
    • @skeletalbassman,是的,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2019-03-10
    • 2013-08-25
    • 2023-03-22
    • 2015-12-30
    • 2017-07-09
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    相关资源
    最近更新 更多