用户命令行?

时间:2013-08-30 21:54:50

标签: python python-3.x

用户是否可以通过使用函数在python中输入命令? 像这样:

#run - command to send user input
def run(execute):
    execute

#program example
command = input("Type in your command: ")
run(command)

此外,可以添加循环以创建无限循环,直到输入“END”,因为此功能已经处于IDLE状态,我正在讨论运行.py文件并使用它来创建文件,例如

用户可以输入create=open("file.txt","w")但它会有效吗?如果不能如何使用,以便用户可以使用程序员创建的命令,例如在此代码中:

#run - command to send user input
def run(execute):
    execute

#Example command
def example(text):
    f = open("user.txt", "w+")
    f.write(text)
    f.close()

#program example
command = input("Type in your command: ")
run(command)

如果用户输入example("hello world!")

,它会起作用吗?

1 个答案:

答案 0 :(得分:2)

您可以使用内置的exec

>>> exec(input('Input a command: '))
Input a command: print(1+1)
2
>>>

但是请注意,这应该与阳离子一起使用 - 它将作为真正的Python代码运行在那里。

相关问题