Executing an R script in python via subprocess.Popen

前端 未结 5 578
逝去的感伤
逝去的感伤 2021-01-20 23:25

When I execute the script in R, it is:

$ R --vanilla --args test_matrix.csv < hierarchical_clustering.R > out.txt

In Python, it works if

5条回答
  •  無奈伤痛
    2021-01-21 00:07

    A couple of ideas:

    1. You might want to consider using the Rscript frontend, which makes running scripts easier; you can pass the script filename directly as a parameter, and do not need to read the script in through standard input.
    2. You don't need the shell for just redirecting standard output to a file, you can do that directly with subprocess.Popen.

    Example:

    import subprocess
    
    output_name = 'something'
    script_filename = 'hierarchical_clustering.R'
    param_filename = '%s_DM_Instances_R.csv' % output_name
    result_filename = '%s_out.txt' % output_name
    with open(result_filename, 'wb') as result:
        process = subprocess.Popen(['Rscript', script_filename, param_filename],
                                   stdout=result);
        process.wait()
    

提交回复
热议问题