You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过Python调用Blue Prism流程:文件夹检测触发执行问题排查

需求可行性与解决方案

需求完全可行

不管用PowerShell还是Python,都能实现文件夹监控+触发Blue Prism流程的功能。先帮你修复现有PowerShell代码的问题,再提供Python版本的实现方案。

修复你的PowerShell代码

你的代码存在两个核心问题:FileSystemWatcher未绑定事件处理逻辑,以及AutomateC的参数格式错误。修复后的完整代码如下:

# 配置参数
$folderPath = "C:\Your\Target\Folder"
$fileFilter = "*.*" # 可按需修改,比如只监控.txt文件
$automateCPath = "C:\Program Files\Blue Prism Limited\Blue Prism Automate\AutomateC.exe"
$bpUser = "admin"
$bpPass = "passw0rd"
$bpProcess = "Test_Profile lookup"
$bpResource = $env:COMPUTERNAME

# 创建文件监控器
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $folderPath
$watcher.Filter = $fileFilter
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true
$watcher.NotifyFilter = [System.IO.NotifyFilters]::FileName -bor [System.IO.NotifyFilters]::LastWrite

# 定义事件处理函数:检测到新文件时触发Blue Prism流程
$onCreated = Register-ObjectEvent $watcher "Created" -Action {
    $filePath = $Event.SourceEventArgs.FullPath
    Write-Host "检测到新文件: $filePath"

    # 等待文件写入完成(避免文件锁定导致Blue Prism无法读取)
    do {
        try {
            $fileStream = [System.IO.File]::Open($filePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
            $fileStream.Close()
            break
        } catch {
            Start-Sleep -Milliseconds 500
        }
    } while ($true)

    # 修正AutomateC参数格式:密码需用/password显式指定
    $arguments = @(
        "/run",
        "/resourcepc", "`"$bpResource`"",
        "/process", "`"$bpProcess`"",
        "/user", $bpUser,
        "/password", $bpPass
    )
    Start-Process -FilePath $automateCPath -ArgumentList $arguments -NoNewWindow -Wait -PassThru
}

# 保持脚本运行
Write-Host "正在监控文件夹: $folderPath"
Write-Host "按Ctrl+C停止监控"
try {
    while ($true) { Start-Sleep 1 }
} finally {
    Unregister-Event -SourceIdentifier $onCreated.Name
    $watcher.Dispose()
}

关键修复点:

  • 给FileSystemWatcher绑定了Created事件处理逻辑,检测到新文件时才会触发流程调用
  • 修正AutomateC参数:密码必须通过/password参数显式传递,之前的写法会被识别为无效参数
  • 添加文件锁定检测,确保文件完全写入后再调用流程,避免读取失败

Python实现方案

如果需要用Python实现,可使用watchdog第三方库监控文件夹,通过subprocess调用AutomateC。

步骤1:安装依赖

pip install watchdog

步骤2:Python代码

import time
import subprocess
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os

# 配置参数
FOLDER_PATH = r"C:\Your\Target\Folder"
FILE_FILTER = "*.*"
AUTOMATEC_PATH = r"C:\Program Files\Blue Prism Limited\Blue Prism Automate\AutomateC.exe"
BP_USER = "admin"
BP_PASS = "passw0rd"
BP_PROCESS = "Test_Profile lookup"
BP_RESOURCE = os.environ["COMPUTERNAME"]

class FolderMonitorHandler(FileSystemEventHandler):
    def on_created(self, event):
        if not event.is_directory:
            file_path = event.src_path
            print(f"检测到新文件: {file_path}")

            # 等待文件写入完成,避免锁定
            while True:
                try:
                    with open(file_path, "r+b"):
                        break
                except PermissionError:
                    time.sleep(0.5)

            # 构造AutomateC调用参数
            args = [
                AUTOMATEC_PATH,
                "/run",
                "/resourcepc", f'"{BP_RESOURCE}"',
                "/process", f'"{BP_PROCESS}"',
                "/user", BP_USER,
                "/password", BP_PASS
            ]

            # 调用Blue Prism流程并捕获结果
            try:
                result = subprocess.run(args, check=True, capture_output=True, text=True)
                print(f"流程调用成功: {result.stdout}")
            except subprocess.CalledProcessError as e:
                print(f"流程调用失败: {e.stderr}")

if __name__ == "__main__":
    event_handler = FolderMonitorHandler()
    observer = Observer()
    observer.schedule(event_handler, path=FOLDER_PATH, recursive=False)
    observer.start()
    print(f"正在监控文件夹: {FOLDER_PATH}")
    print("按Ctrl+C停止监控")
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

说明:

  • watchdog提供跨平台的文件系统监控能力,比Windows专属的FileSystemWatcher更通用
  • 同样包含文件锁定检测逻辑,确保文件可正常读取
  • 使用subprocess.run调用AutomateC,便于捕获执行结果和错误信息

内容的提问来源于stack exchange,提问作者ac98521

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 16:21:00