如何将 Python 转义字符与 MatLab 命令结合使用?



以下命令在我连接到我想要打开的计算机后起作用。

cd /Volumes/promiseraid9/workspace/sarah2/Facility/; /Applications/MATLAB_R2017a.app/bin/matlab -r "cd /volumes/promiseraid9/workspace/colleen/NewResiduals/j078_8; try, run('ABOVE2019_TF01_MatLabCommands_Test.m'); end; cd /Volumes/promiseraid9/workspace/sarah2/Facility; resid_process_GPS(in_dir_list,out_dir_list);"

但是,我希望能够从python脚本中使用ssh并使用上述命令,但使其完全如上所示(意味着所有相同的"和"s"(

所以我的问题是处理转义字符...

os.system('ssh -t cmbrook3@gs694-vegasx2.gsfc.nasa.gov 'cd /Volumes/promiseraid9/workspace/sarah2/Facility/; /Applications/MATLAB_R2017a.app/bin/matlab -r "cd /volumes/promiseraid9/workspace/colleen/NewResiduals/j078_8; try, run('ABOVE2019_TF01_MatLabCommands_Test.m'); end; cd /Volumes/promiseraid9/workspace/sarah2/Facility; resid_process_GPS(in_dir_list,out_dir_list); end;"'')

主要问题是 MatLab 看到的 run(\'ABOVE2019_TF01_MatLabCommands_Test.m\'( 与 run('ABOVE2019_TF01_MatLabCommands_Test.m'( 完全一样。

那么在这种情况下我可以使用什么样的转义字符呢?

您可以将命令放入三引号中,如下所示:

command_to_run = (
'''ssh -t cmbrook3@gs694-vegasx2.gsfc.nasa.gov'''
''' 'cd /Volumes/promiseraid9/workspace/sarah2/Facility/; '''
'''/Applications/MATLAB_R2017a.app/bin/matlab -r '''
'''"cd /volumes/promiseraid9/workspace/colleen/NewResiduals/j078_8;'''
'''try, run ABOVE2019_TF01_MatLabCommands_Test.m; end; '''
'''cd /Volumes/promiseraid9/workspace/sarah2/Facility;'''
''' resid_process_GPS(in_dir_list,out_dir_list);"' '''
).strip()# command_to_run is a string
os.system(command_to_run)

三引号允许您将引号放入字符串中而不转义它们。

编辑:使用 @ColleenB 建议的修改编辑代码。

Edit2:关于strip函数的更多解释,我用它来删除最后一个空格。没有它,Python 无法解释最后三个引号(我也可以使用三重双引号而不是简单的引号(。

括号允许将字符串拆分为许多行,而不是很长的行。

最新更新