调试:从Windows任务管理器运行Python脚本

时间:2016-10-23 01:29:42

标签: python python-3.x

我正在尝试使用Windows任务计划程序运行Python程序。在规定的时间,我看到命令窗口短暂出现然后消失。但是Python脚本应该创建一个文件。永远不会创建该文件。我使用Windows搜索搜索文件,但它不在任何地方。但是,当我使用命令行运行脚本时,文件将按预期创建。我做错了什么?

以下是我的设置:

Python程序: ---------------------

import os

print('start of simple test')
testList ="1,2,3"
with open('lala.txt', 'w') as testfile:
    testfile.write(testList)

---------------------

以下是我的Windows 7任务计划程序窗口中的操作设置 程序/脚本:C:\ Python \ python.exe 添加参数:" C:\ PythonProject \ ReportCreator.py"

Screenshot

1 个答案:

答案 0 :(得分:2)

您可以使用此代码查看调度程序在哪个文件夹中运行ReportCreator.py。创建一个python文件scheduler_path.py并使用调度程序运行它:

import os

print('current path:', os.path.abspath(os.curdir))
input('press enter to continue')  # input is for Python3. Use raw_input for Python2

它给了我这个输出:current path: C:\WINDOWS\system32。我的猜测是它试图写入system32文件夹,但没有权限这样做。

您可以提供写入文件的绝对路径,或者如果要在与脚本文件相同的文件夹中创建它,则可以执行以下操作:

import os

print('start of simple test')
test_list ='1,2,3'
script_folder = os.path.dirname(__file__)  # in your case this should become C:\PythonProject\
filename = 'lala.txt'
filepath = os.path.join(script_folder, filename)
with open(filepath, 'wt') as test_file:
    test_file.write(test_list)