将Ipython变量作为字符串参数传递给Shell命令 [英] Passing Ipython variables as string arguments to shell command

查看:174
本文介绍了将Ipython变量作为字符串参数传递给Shell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I execute a shell command from Ipython/Jupyter notebook passing the value of a python string variable as a string in the bash argument like in this example:

sp_name = 'littleGuy' #the variable

sp_details = !az ad app list --filter "DisplayName eq '$sp_name'" #the shell command

我尝试单独使用$sp_name${sp_name}{sp_name}等,如

I've tried using $sp_name alone, ${sp_name}, {sp_name} etc as outlined in this related question, but none have worked.

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

The kicker here is the variable name needs to be quoted as a string in the shell command.

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

@manu190466. I was judging from the string output that your solution worked. It appears for some reason it does not in practice. I wonder if az ad app list URL encodes the query or something...?

有想法吗?

推荐答案

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

The main problem you encounters seems to come from the quotes needed in your string. You can keep the quotes in your string by using a format instruction and a raw string.

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

Use a 'r' before the whole string to indicate it is to be read as raw string, ie: special caracters have to not be interpreted. A raw string is not strictly required in your case because the string constructor of python is able to keep single quotes in a double quotes declaration but I think it's a good habit to use raw string declarators when there are non alphanumerics in it.

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

There are at least two way to format strings :

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

Older method herited from ancient langages with % symbols:

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

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

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

Newer method with {} symbols and the format() method :

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

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

这篇关于将Ipython变量作为字符串参数传递给Shell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆