python运行shell指令传参数,将Ipython变量作为字符串参数传递给Shell命令

"本文指导如何在Jupyter Notebook中使用变量sp_name='littleGuy'执行shell命令,如`azadapplist --filter "DisplayName eq '$sp_name'"`。解决引号困扰的方法包括使用格式化字符串和raw字符串,提供两种方法供参考:旧方法用`%s`占位符和新方法用`{}
摘要由CSDN通过智能技术生成

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

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

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

EDIT1:

@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...?

Thoughts?

DOfmx.png

解决方案

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.

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}

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}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值