执行>> Julia程序中的shell运算符 [英] Executing the >> shell operator from a Julia program
问题描述
我试图使用反引号从Julia内部添加文件
I was trying to append a file from inside Julia using backticks
run(`cat file2 >> file1`)
但这是行不通的.似乎>>运算符无法正确解释.有什么办法可以通过管道或其他技巧来做到这一点?
but this doesn't work. It seems the >> operator can't be interpreted correctly. Is there some way to do this with a pipeline or other trick?
推荐答案
以下内容将字符串作为文字shell脚本运行,从而规避了Julia为您设置的安全性:
The following will run a string as a literal shell script, circumventing the safeties Julia sets up for you:
script = "cat file2 >> file1"
run(`sh -c $script`)
假设已设置file1
和file2
的参数,则以下内容更安全(不易受到外壳注入攻击,因为它会从脚本文本中带外通过file1
和file2
): /p>
Assuming that file1
and file2
are parameterized, the following is a safer equivalent (not prone to shell injection attacks, as it passes file1
and file2
out-of-band from script text):
script = "cat \"\$1\" >> \"\$2\""
source = "file1"
dest = "file2"
run(`sh -c $script _ $source $dest`)
这会将_
传递为$ 0,将file1
传递为$1
,并且将file2
传递为$2
.
This passes _
as $0, file1
as $1
, and file2
as $2
.
最后,要完全避免使用shell,请指定stdout=
作为文件句柄:
Finally, to avoid a shell altogether, specify stdout=
to be your file handle:
source = "file1"
dest = "file2"
run(pipeline(`cat $source`, stdout=open(dest, "a")))
这篇关于执行>> Julia程序中的shell运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!