从R调用Python-使用双引号分配变量字符串
我编写了一个Python函数,允许我对任何文件夹中的所有文件重复命令:从R调用Python-使用双引号分配变量字符串,python,r,escaping,Python,R,Escaping,我编写了一个Python函数,允许我对任何文件夹中的所有文件重复命令: import os def removeChar(stringVar,removeChars): for znaki in removeChars: stringVar=stringVar.replace(znaki,'') return stringVar def ForAllFiles(path,command='gdal2xyz.py "inputFile" "outputFile"
import os
def removeChar(stringVar,removeChars):
for znaki in removeChars:
stringVar=stringVar.replace(znaki,'')
return stringVar
def ForAllFiles(path,command='gdal2xyz.py "inputFile" "outputFile"',removeChars=[],extension='.tif',newExtension='.txt'):
for root, dirs, files in os.walk(path):
dirs.sort()
for file in files:
if file.endswith(extension):
newFile=removeChar(file,removeChars)
newFile=newFile.replace(extension,newExtension)
cmd=command.replace('inputFile',os.path.join(root,file))
cmd=cmd.replace('outputFile',os.path.join(root,newFile))
os.system(cmd)
我希望在R中分配一些Python变量(路径、命令)!然后从R执行这个函数!
提到的一个变量包含文件名为('inputFile')的命令,因此我希望用双引号将文件名括起来
当我打电话时:
library(rPython)
python.assign("variable",'my "variable"')
我收到一个错误:
wpython.exec(python.command):
应为分隔符:第1行第9列(字符8)
因此,我认为这足以避免双重引用:
python.assign("variable",'my \"variable\"')
python.assign("variable","my \"variable\"")
但它也不工作,并产生错误消息
所以我最后的想法是:
python.assign("variable","my " + python.exec("chr(34)") + "variable" + python.exec("chr(34)"))
但是它也失败了你试过Python代码吗?它显然有错误。@pacholik你是对的-我忘了我在Python脚本中定义了额外的函数“removeChar”。我插入了它-很抱歉。@pacholik我测试过-如果您将我的脚本复制并粘贴到Python中,并至少定义路径和命令,它将正常工作(例如:command='ls“inputFile”'和ForAllFiles(path,command))。