R脚本自动化时的结果不同

Geo*_*tas 7 windows redirect automation r ghostscript

以下命令在pdf文件上执行ghostscript.(该pdf_file变量包含该pdf的路径)

bbox <- system(paste( "C:/gs/gs8.64/bin/gswin32c.exe -sDEVICE=bbox -dNOPAUSE -dBATCH -f", pdf_file, "2>&1" ), intern=TRUE)
Run Code Online (Sandbox Code Playgroud)

执行后bbox包含以下字符串.

GPL Ghostscript 8.64 (2009-02-03)
Copyright (C) 2009 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Processing pages 1 through 1.
Page 1
%%BoundingBox: 36 2544 248 2825
%%HiResBoundingBox: 36.395015 2544.659922 247.070032 2824.685914
Error: /undefinedfilename in (2>&1)
Operand stack:

Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   --nostringval--   false   1   %stopped_push
Dictionary stack:
   --dict:1147/1684(ro)(G)--   --dict:1/20(G)--   --dict:69/200(L)--
Current allocation mode is local
Last OS error: No such file or directory
GPL Ghostscript 8.64: Unrecoverable error, exit code 1
Run Code Online (Sandbox Code Playgroud)

然后操纵该字符串,以便隔离BoundingBox尺寸(36 2544 248 2825)并用于裁剪pdf文件.到目前为止一切正常.

但是,当我在任务管理器中安排此脚本(使用Rscript.exe或Rcmd.exe BATCH),或者当脚本在R块中并且我按下时knit HTML,bbox获取以下缺少BoundingBox信息的字符串,并使其成为不可用:

GPL Ghostscript 8.64 (2009-02-03)
Copyright (C) 2009 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Processing pages 1 through 1.
Page 1
Error: /undefinedfilename in (2>&1)
Operand stack:

Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   --nostringval--   false   1   %stopped_push
Dictionary stack:
   --dict:1147/1684(ro)(G)--   --dict:1/20(G)--   --dict:69/200(L)--
Current allocation mode is local
Last OS error: No such file or directory
Run Code Online (Sandbox Code Playgroud)

如何解决此问题并让脚本自动运行?

(该脚本来自该问题的接受答案)

ixe*_*013 6

2>&1您添加在命令的末尾被送到Ghostscript的解释,而不是shell.Ghostscript将其解释为文件,因此出错.我使用procmon来查看进程创建:

stderr重定向被ghostscript视为文件

要使shell解释它,必须在命令前加上cmd /c,如下所示

> bbox <- system(paste("cmd /c C:/Progra~1/gs/gs9.07/bin/gswin64c.exe -sDEVICE=bbox -dNOPAUSE -dBATCH -q -f",pdf_file,"2>&1"), intern=TRUE)
> print (bbox)
[1] "%%BoundingBox: 28 37 584 691"                                  "%%HiResBoundingBox: 28.997999 37.511999 583.991982 690.839979"
Run Code Online (Sandbox Code Playgroud)