Skip to main content
 首页 » 编程设计

python之为什么任务管理器不运行脚本中的某些代码行

2025年05月04日16youxin

这里是 Python 新手。

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

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

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

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

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

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

有什么想法吗?

请您参考如下方法:

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

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

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)

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

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

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