将Ipython变量作为字符串参数传递给Shell命令

时间:2020-05-05 04:56:51

标签: python shell ipython

如何从Ipython / Jupyter笔记本执行shell命令,将python字符串变量的值作为字符串传递给bash参数中的字符串,如下例所示:

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
<!-- Configurations that affect the Test Framework -->
<!-- Configurations for data collectors -->
<DataCollectionRunSettings>
<DataCollectors>
 <DataCollector uri="datacollector://microsoft/VideoRecorder/1.0" assemblyQualifiedName="Microsoft.VisualStudio.TestTools.DataCollection.VideoRecorder.VideoRecorderDataCollector, Microsoft.VisualStudio.TestTools.DataCollection.VideoRecorder, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" friendlyName="Screen and Voice Recorder">
 <!--Video data collector was introduced in Visual Studio 2017 version 15.5 -->
 </DataCollector>
</DataCollectors>
</DataCollectionRunSettings>
</RunSettings>

我尝试单独使用sp_name = 'littleGuy' #the variable sp_details = !az ad app list --filter "DisplayName eq '$sp_name'" #the shell command $sp_name${sp_name}等(如this related question中所述),但没有一个起作用。

这里的关键是变量名称,需要在shell命令中用字符串引用。

EDIT1:

@ manu190466。我从字符串输出判断您的解决方案有效。由于某种原因,它似乎在实践中没有出现。我想知道{sp_name} URL是否对查询进行编码?

有想法吗?

enter image description here

3 个答案:

答案 0 :(得分:4)

您遇到的主要问题似乎来自字符串中所需的引号。 您可以使用格式指令和原始字符串将引号保留在字符串中。

在整个字符串前使用'r'表示将其作为原始字符串读取,即:不必解释特殊字符。在您的情况下,未严格要求使用原始字符串,因为python的字符串构造函数能够在双引号声明中保留单引号,但是我认为在其中包含非字母数字时使用原始字符串声明符是一种好习惯。

至少有两种格式化字符串的方法:

继承自带有%符号的古代语言的较旧方法:

sp_name = 'littleGuy' #the variable
sp_query = r"DisplayName eq '%s'"%(sp_name) 

sp_details = !az ad app list --filter {sp_query}

带有{}符号和format()方法的较新方法:

sp_name = 'littleGuy' #the variable
sp_query = r"DisplayName eq '{}'".format(sp_name) 

sp_details = !az ad app list --filter {sp_query}

答案 1 :(得分:0)

您会尝试这样的事情吗?

sp_name = 'littleGuy' #the variable
sp_query = "DisplayName eq "+sp_name 

sp_details = !az ad app list --filter {sp_query}

答案 2 :(得分:0)

也可以使用下面的方法解决该问题

sp_name = 'littleGuy' #the variable
sp_details = !az ad app list --filter "DisplayName eq '{sp_name}'"