带变量的 Python 子进程调用

问题描述:

我目前正在为客户编写脚本.

I am currently writing a script for a customer.

此脚本从配置文件中读取.然后将其中一些信息存储在变量中.

This script reads from a config file. Some of these infos are then stores in variables.

之后我想使用 subprocess.call 来执行一个挂载命令所以我使用这些变量来构建挂载命令

Afterwards I want to use subprocess.call to execute a mount command So I am using these variables to build the mount command

call("mount -t cifs //%s/%s %s -o username=%s" % (shareServer, cifsShare, mountPoint, shareUser))

然而这不起作用

Traceback (most recent call last):
  File "mount_execute.py", line 50, in <module>
    main()
  File "mount_execute.py", line 47, in main
    call("mount -t cifs //%s/%s %s -o username=%s" % (shareServer, cifsShare, mountPoint, shareUser))
  File "/usr/lib64/python2.6/subprocess.py", line 470, in call
return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib64/python2.6/subprocess.py", line 623, in __init__
errread, errwrite)
  File "/usr/lib64/python2.6/subprocess.py", line 1141, in _execute_child
   raise child_exception
 OSError: [Errno 2] No such file or directory

首先使用

mountCommand = 'mount -t cifs //%s/%s %s -o username=%s' % (shareServer, cifsShare, mountPoint, shareUser)
call(mountCommand)

也会导致同样的错误.

您当前的调用是为与 shell=True 一起使用而编写的,但实际上并未使用它.如果您真的想使用需要用shell解析的字符串,请使用call(yourCommandString, shell=True).

Your current invocation is written for use with shell=True, but doesn't actually use it. If you really want to use a string that needs to be parsed with a shell, use call(yourCommandString, shell=True).

更好的方法是传递一个明确的参数列表——使用 shell=True 使命令行解析依赖于数据的细节,而传递一个明确的列表意味着你正在制作自己做出解析决定(作为了解您正在运行的命令的人,您更适合做这些决定).

The better approach is to pass an explicit argument list -- using shell=True makes the command-line parsing dependent on the details of the data, whereas passing an explicit list means you're making the parsing decisions yourself (which you, as a human who understands the command you're running, are better-suited to do).

call(['mount',
      '-t', 'cifs',
      '//%s/%s' % (shareServer, cifsShare),
      mountPoint,
      '-o', 'username=%s' % shareUser])