使用变量从python执行shell脚本

2024-06-17 15:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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 <module>
    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 "<string>", line 1, in <lambda>
  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

Tags: inpycmdbinmaindomainlibusr
3条回答

我也希望做同样的事情作为这篇文章。使用变量执行python中的Shell脚本(我认为使用变量意味着使用命令行参数)

为了得到结果,我做了以下工作。我分享的情况下,其他人正在寻找相同的答案

    import os
    arglist = 'arg1 arg2 arg3'
    bashCommand = "/bin/bash script.sh " + arglist 
    os.system(bashCommand)

这对我来说很好

我还建议,在阅读了更多的内容后,如果您希望返回结果以供显示,最好使用subprocess.Popen。我将所有内容都记录到bash脚本中的另一个文件中,因此我实际上不需要子流程

我希望有帮助

    import os
    os.system("cat /root/test.sh")
    #!/bin/bash
    x='1'
    while [[ $x -le 10 ]] ; do
      echo $x: hello $1 $2 $3
      sleep 1
      x=$(( $x + 1 ))
    done

    arglist = 'arg1 arg2 arg3'
    bashCommand = 'bash /root/test.sh ' + arglist
    os.system(bashCommand)
    1: hello arg1 arg2 arg3
    2: hello arg1 arg2 arg3
    3: hello arg1 arg2 arg3
    4: hello arg1 arg2 arg3
    5: hello arg1 arg2 arg3

像这样

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

文件可在python website上查阅

要记住的简单解决方案:

import os
bashCommand = "source script.sh"
os.system(bashCommand)

相关问题 更多 >