【问题标题】:Run Python file with FileSystemWatcher from Powershellscript使用 Powershell 脚本中的 FileSystemWatcher 运行 Python 文件
【发布时间】:2018-05-11 14:22:33
【问题描述】:

对于了解 Powershell 的人来说,这可能是一个简单的问题。我已经尝试过实现类似问题的几个答案的建议,例如thesethese。我有一个文件监视器,它监视文件夹并在发生更改时写入日志文件。这很好用。

我没能做的是执行一个额外的 Python 脚本。我很感激任何建议。

$folder = 'F:\myPath\myFolder' # Enter the root path you want to monitor.
$filter = '*.*'  # You can enter a wildcard filter here.

# In the following line, you can change 'IncludeSubdirectories to $true if required.                          
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

# Registered events:
Register-ObjectEvent $fsw Renamed -SourceIdentifier FileRenamed -Action {
$OldName = $Event.SourceEventArgs.OldName
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore white
Out-File -FilePath F:\myPath\myLogFile.txt -Append -InputObject "The file $name was $changeType at $timeStamp"
python F:\myPath\myPythonScript.py}

如何使用 Powershell ISE 实现这一目标?

【问题讨论】:

    标签: powershell filesystemwatcher


    【解决方案1】:

    使用 Powershell 控制台比使用 ISE 更幸运。如果您已将 Python 添加到您的 PATH,那么它就像 python F:\myPath\myPythonScript.py 一样简单

    如果 Python 脚本返回任何值,为了将它们传回 Powershell,您需要将它们打印到屏幕上,它们将按照返回的顺序存储为数组。

    【讨论】:

    • 你是对的:如果我只在控制台中输入命令python F:\myPath\myPythonScript.py,Python 脚本就会运行。但是当我在 Powershell 控制台中运行整个脚本(包括 filesystemwatcher)时,当我更改监视文件夹中的文件时,Python 脚本不会运行。那么,如果监视文件夹中的文件发生更改,如何让 Python 脚本运行?
    • EventSubscriber 所做的只是执行-Action 后面大括号中的代码。那里的代码是否正确执行?例如,它是否写入日志文件?
    • 是的,代码正确执行并写入日志文件。但它没有在控制台中执行python脚本。我编辑了我正在使用的问题和代码。
    • Python脚本的内容是什么?
    • 这是 Python 脚本的内容:# -*- coding: utf-8 -*- print "Hello World!"
    猜你喜欢
    • 2018-08-12
    • 1970-01-01
    • 2019-04-17
    • 2019-01-19
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    相关资源
    最近更新 更多