0

I have a command saved in a text file that I wish to execute using subprocess.run() from R using the reticulate package.

I have a directory with three files:

  • test_command.txt which contains the command 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")

When I run run_command.py directly, foo.txt is created, and True is returned.

However, when I run from R using run_from_r.R, I get the following message:

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") runs properly in R.

Any idea what this error message means, and how I can make the command run properly when running using subprocess.check_output/run and reticulate?

Thanks!

DanielWard
  • 71
  • 3
  • 7

1 Answers1

0

I seem to have fixed it by using:

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

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

DanielWard
  • 71
  • 3
  • 7