使用变量从Python执行shell脚本

11

我有这段代码:

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
4个回答

16

像这样吗?

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

可在Python官网上查阅文档。


我也是。如果它期望一个字符串,而你有一个整数,只需将其转换即可。 - Paco

4

我也在寻求与此帖子相同的事情。使用变量从python执行Shell脚本(我认为这意味着使用命令行参数)。

我以下列方式获取了结果。我分享一下,以防其他人正在寻找相同的答案。

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

这对我来说完全没问题。

我还发现,如果您想要获取结果以供显示目的,最好使用subprocess.Popen。我将所有内容记录到另一个文件中,在bash脚本中没有必要使用subprocess。

希望这可以帮助您。

    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

谢谢。将来我会更多地使用Python和Linux Bash,所以下次我可以尝试您的方法;-) - Vince

1
一个记忆简单的解决方案:

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

1
是的,但如何附加变量“domid”的值? - Vince

0
你需要从你的Python脚本中以以下方式调用shell脚本:
subprocess.call(['test.sh', domid])

请参考这里获取subprocess模块的文档。在上面的脚本中,我们将一个列表传递给call方法,其中第一个元素是要执行的程序,列表中剩余的元素是程序的参数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接