Skip to main content
 首页 » 编程设计

python之为什么 exec() 命令运行时没有错误,但没有产生预期的输出

2025年04月02日8linjiqin

我正在创建一个非常基本的 python 程序,它允许用户输入一个命令,然后该命令作为代码运行。

例如,我导入了一个名为 textScripts.py 的文件:在该文件中有一个名为 createFile() 的函数。当用户输入 textScripts.createFile() 时,它被传递到 exec()。它运行无误并退出程序,但未创建文件!

我知道 createFile() 函数有效,因为如果我将 textScripts.createFile() 放入代码中,它会创建一个文件。

这里是相关的代码片段:

commandList=[] 
while(commandRun): 
    count = 0 
    commandList.append(input(">>>")) 
    exec(commandList[count]) 
    print(commandList[count]) 
    count += 1 

here is a screenshot of the code being run:

>>> textScripts.createFile() 
>>> 

here is a screenshot of the folder:

__pyCache__ 
textScripts.py 
CLIFile.py 

这个文件夹里应该有一个文件

这里是函数createFile():

def createFile( 
    destination = os.path.dirname(__file__), 
    text = "Sick With the Python\n" 
    ): 
    ''' createFile(destination, text) 
 
        This script creates a text file at the 
        Specified location with a name based on date 
    ''' 
    date = t.localtime(t.time()) 
    name = "%d_%d_%d.txt" %(date[1], date[2], date[0]) 
 
    if not(os.path.isfile(destination + name)): 
        f = open(destination + name, "w") 
        f.write( text ) 
        f.close 
    else: 
        print("file already exists") 

如果这是一个明显的问题,我提前道歉;我是 python 的新手,一直在寻找几个小时的答案来解释为什么会发生这种情况。

请您参考如下方法:

您将文件保存到错误的文件夹(您可以在您的函数中插入“打印(目标+名称)”)

你需要替换这个:

destination + name 

为此:

os.path.join(destination, name) 

附言:

  1. 您没有关闭文件 (f.close -> f.close())
  2. 打开任何资源的最佳方式是使用“with”。

例如:

with open('file.txt', 'w') as f: 
    f.write('line')