【问题标题】:Subprocess run works from Python, but not when using R and Reticulate子进程运行在 Python 中有效,但在使用 R 和 Reticulate 时无效
【发布时间】:2020-11-10 22:43:16
【问题描述】:

我有一个保存在文本文件中的命令,我希望使用 R 中的 subprocess.run() 使用 reticulate 包执行该命令。

我有一个包含三个文件的目录:

  • test_command.txt 包含命令touch foo.txt

  • run_command.py:

import subprocess
import os

subprocess.check_output('bash test_command.txt')
print(os.path.isfile("foo.txt"))  # Check if the command was actually executed properly
  • run_from_r.R:
library(reticulate)
use_condaenv("my_env")  # Same conda environment as used for python
source_python("run_command.py")

当我直接运行run_command.py时,会创建foo.txt,并返回True

但是,当我使用 run_from_r.R 从 R 运行时,我收到以下消息:

Error in py_run_file_impl(file, local, convert) : 
  OSError: [WinError 6] The handle is invalid

Detailed traceback: 
  File "<string>", line 5, in <module>
  File "C:\Users\Danie\miniconda3\envs\wildcats_summer_env\lib\subprocess.py", line 411, in check_output
    **kwargs).stdout
  File "C:\Users\Danie\miniconda3\envs\wildcats_summer_env\lib\subprocess.py", line 488, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Users\Danie\miniconda3\envs\wildcats_summer_env\lib\subprocess.py", line 753, in __init__
    errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  File "C:\Users\Danie\miniconda3\envs\wildcats_summer_env\lib\subprocess.py", line 1054, in _get_handles
    p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)

system("bash test_command.txt") 在 R 中正常运行。

知道此错误消息的含义,以及在使用subprocess.check_output/runreticulate 运行时如何使命令正常运行?

谢谢!

【问题讨论】:

    标签: python r subprocess reticulate


    【解决方案1】:

    我似乎已通过以下方式修复它:

    subprocess.run(['bash', 'test_command.txt'], stdout=subprocess.PIPE,
                   stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
    

    来自Python running as Windows Service: OSError: [WinError 6] The handle is invalid

    【讨论】:

      猜你喜欢
      • 2021-08-09
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 2021-11-26
      相关资源
      最近更新 更多