如何从python执行os/shell命令

问题描述:

对于在终端中说我做了cd Desktop你应该知道它会将你移动到那个目录下,但是我如何在python中执行该操作,但是使用Desktop的raw_input("")来执行我的命令?如何从python执行os/shell命令

+0

您是否在问如何通过Python中的raw_input执行shell/cmd命令? –

+0

查克洛根是正确的谢谢你知道理解我的问题 –

+0

查克洛根我检查出没有raw_input的迹象,因为我看到 –

下面的代码读取的raw_input使用你的命令,并使用使用os.system()

import os 

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

最好的问候, 亚龙执行它

+0

当使用代码时cd不会工作 –

+0

请参阅下面的问题和解决办法“cd”http://stackoverflow.com/questions/35843054/change-directory- in-terminal-using-python/35843532#35843532 – Yaron

+0

当我打开文件并执行cd/home/pi/Desktop/asf1/dos时,什么也没有发生 –

也许你可以这样做:

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

了解详情,你可以搜索subprocess模块

+0

如'subprocess'文档中所示,这会在'input =“ls -l”'的情况下引发错误。你需要用'space'字符来'分割'输入字符串,以便给出'subprocess.call()'它可以使用的东西(一个列表)。 – skeletalbassman

+0

@skeletalbassman,是的,谢谢。 –

+0

使用'shlex.split' – warvariuc

去与你的具体的例子,你会做到以下几点:

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 

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