在 python 3 中使用子进程模块时如何避免 WinError 5

How to avoid WinError 5 when using subprocess module in python 3

我正在尝试将 subprocess 模块用于 运行 词性标注器 (TreeTagger)。我已经在 D:/TreeTagger 进行了设置,并且在我的终端上使用它没有问题,这是一个示例:

tag-french test.txt output.txt

假设我们在上述目录中。我正在尝试使用 python:

做同样的事情
subprocess.run([r"D:/TreeTagger", "tag-french", input_file, output_file])

其中运行进入以下PermissionError

Traceback (most recent call last):
  File "tagger.py", line 29, in <module>
    tag_file(input_file=str(input), output_file=str(output))
  File "tagger.py", line 17, in tag_file
    subprocess.run([r"D:/TreeTagger", "tag-french", input_file, output_file])
  File "D:\Anaconda\lib\subprocess.py", line 472, in run
    with Popen(*popenargs, **kwargs) as process:
  File "D:\Anaconda\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "D:\Anaconda\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
PermissionError: [WinError 5] Access is denied

现在我明白这是由于第一个参数引起的,因为它不会更改目录。我的 python 代码与 TreeTagger 位于不同的目录中。我相信这是错误的根源,但我不知道如何解决这个问题。

诚然,这个问题遗漏了一个非常重要的问题,即 D:/TreeTagger 中的文件是如何排列的,这是问题的根本原因。 tag-french 不是可执行文件,而是 windows 批处理文件。因此,我没有访问这个文件,而是通过直接调用可执行文件和参数文件来绕过这一步。这是与之相关的代码部分:

tagger_location = Path(r"D:/TreeTagger")
    param_file = tagger_location / 'lib' / 'french.par'
    process = subprocess.Popen([str(tagger_location / 'bin' / 'tree-tagger.exe'),
                                str(param_file),
                                input_file,
                                output_file])
    stdout, stderror = process.communicate()
    print("Stdout is -> ", stdout)
    print("StdError is -> ", stderror)
    print("Done and saved to ", output_file)

希望这能解决将来可能遇到的类似问题。