为什么任务管理器没有 运行 脚本中的某些代码行?

Why does Task Manager not run some lines of code in script?

Python新手在此

我有一个执行某些地理数据库管理(reconcile/post 版本、压缩等)的 Python 脚本。我的脚本中有以下代码行:

createLog = open(str(datetime.date.today()) + ".txt", "w")

沿着我添加到文本文件的脚本的每个步骤,包含以下语句:

createLog.write("Database connections blocked.\n")

当我 运行 我的 IDE (PyCharm) 中的脚本时,我得到了想要的结果:一个文本文件,每个步骤都写入 .txt 文件。当我 运行 它在任务计划程序中时,没有创建 .txt 文件,因此没有日志。据我所知,其他所有内容 运行s。我能够跟踪对数据所做的编辑。

我以前在使用任务计划程序时遇到过类似的事情,但过去从未解决过这个问题。

有什么想法吗?

我认为这是一个工作目录问题。 Python 的打开函数在当前工作目录中打开一个文件,而不是在与脚本相同的文件夹中。这是一个普遍的误解! (这让我在学习时困惑了很久 Python...)

那么什么是工作目录?好吧引用我的好朋友维基百科:

In computing, the working directory of a process is a directory of a hierarchical file system, if any,[1] dynamically associated with each process. When the process refers to a file using a simple file name or relative path (as opposed to a file designated by a full path from a root directory), the reference is interpreted relative to the current working directory of the process. So for example a process with working directory /rabbit-shoes that asks to create the file foo.txt will end up creating the file /rabbit-shoes/foo.txt.

(来源:https://en.wikipedia.org/wiki/Working_directory

那么这个工作目录是如何选择的呢?

嗯,它是由那个进程的父进程选择的!当您 运行 来自 shell 的程序时,例如 bash,shell(父进程)有助于设置您正在 运行ning 的程序的工作目录(子进程)到您当前所在的目录。(即您 cd 到的目录。)

由于您的 IDE 聪明且乐于助人,它正在启动您的 Python 脚本进程并将工作目录设置为脚本本身所在的同一位置。任务调度程序的帮助不大......我完全不知道它正在将工作目录设置为什么。但是,如果您搜索系统,我相信您会在某处找到日志文件!