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

Why is exec() command running with no errors but not producing the expected output?

我正在创建一个非常基本的 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 的新手,一直在寻找几个小时的答案来解释为什么会发生这种情况。

您将文件保存到错误的文件夹(您可以在函数中插入 "print(destination + name)")

你需要替换这个:

destination + name

对此:

os.path.join(destination, name)

PS:

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

例如:

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