python 执行shell_从python执行Shell脚本与变量

在尝试从Python代码中使用`subprocess.call`执行一个带参数的shell脚本时遇到了错误。代码尝试将变量`domid`作为参数传递给`test.sh`,但出现了`TypeError: execv() arg2 must contain only strings`。这表明传递给`execv()`的参数列表中可能包含了非字符串元素。解决方案是确保所有参数都被转换为字符串。
摘要由CSDN通过智能技术生成

我有这个代码:

opts.info("Started domain %s (id=%d)" % (dom,domid))

我想从上面执行一个带有参数domid的shell脚本.

这样的东西

subprocess.call(['test.sh %d',domid])

它是如何工作的?

我试过了:

subprocess.call(['test.sh',domid])

但是我收到这个错误:

File "/usr/lib/xen-4.1/bin/xm",line 8,in

main.main(sys.argv)

File "/usr/lib/xen-4.1/bin/../lib/python/xen/xm/main.py",line 3983,in main

_,rc = _run_cmd(cmd,cmd_name,args)

File "/usr/lib/xen-4.1/bin/../lib/python/xen/xm/main.py",line 4007,in _run_cmd

return True,cmd(args)

File "",line 1,in

File "/usr/lib/xen-4.1/bin/../lib/python/xen/xm/main.py",line 1519,in xm_importcommand

cmd.main([command] + args)

File "/usr/lib/xen-4.1/bin/../lib/python/xen/xm/create.py",line 1562,in main

dom = make_domain(opts,config)

File "/usr/lib/xen-4.1/bin/../lib/python/xen/xm/create.py",line 1458,in make_domain

subprocess.call(['test.sh',domid])

File "/usr/lib/python2.7/subprocess.py",line 493,in call

return Popen(*popenargs,**kwargs).wait()

File "/usr/lib/python2.7/subprocess.py",line 679,in __init__

errread,errwrite)

File "/usr/lib/python2.7/subprocess.py",line 1249,in _execute_child

raise child_exception

TypeError: execv() arg 2 must contain only strings

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Python脚本中运行Shell脚本并接收多个变量的传参,你可以在`subprocess.run()`函数中使用`subprocess.PIPE`来捕获Shell脚本的输出,并使用`subprocess.communicate()`方法来获取输出结果。 以下是一个示例,演示如何在Python中运行Shell脚本并接收多个变量的传参: Shell脚本(script.sh): ```bash #!/bin/bash # 接收三个参数并输出 echo "第一个参数:$1" echo "第二个参数:$2" echo "第三个参数:$3" ``` Python脚本: ```python import subprocess def run_shell_script(script_path, *args): cmd = ["bash", script_path, *args] result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) output = result.stdout.strip() return output # 运行Shell脚本并传递参数 output = run_shell_script("./script.sh", "value1", "value2", "value3") print(output) ``` 在这个示例中,我们定义了一个名为`run_shell_script()`的函数,该函数接收一个Shell脚本的路径和多个参数。在函数内部,我们构建一个包含Shell命令和参数的列表,并使用`subprocess.run()`函数来运行Shell脚本。 通过设置`stdout=subprocess.PIPE`,我们将Shell脚本的输出捕获到一个变量中。通过`result.stdout.strip()`,我们获取捕获的输出结果,并将其返回。 最后,我们调用`run_shell_script()`函数并传递Shell脚本路径和多个参数。输出结果将被打印出来。 请确保提供正确的Shell脚本路径,并根据实际情况修改参数的值。 希望这个示例能帮助到你!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值