Python 带变量的子进程调用

Python Subprocess Call with variables

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

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

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

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).


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

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