使用变量的Python Subprocess调用

3

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

这个脚本从配置文件中读取信息。 其中一些信息被存储在变量中。

之后,我想使用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)

也会导致相同的错误。

call(['mount', '-t', 'cifs', '//%s/%s' % (shareServer, cifsShare), mountPoint, '-o', 'username=%s' % shareUser]) - Andrea Corbellini
3
相关问题有一个技术上可行的答案,但是不安全,不应使用。因此,我认为不能将这个问题标记为重复,因为其他问题已经有了答案。下面的Charles Duffy的回答要好得多。 - user3553031
1个回答

6

您当前的调用是为使用 shell=True 编写的,但实际上没有使用它。如果您确实想要使用需要使用 shell 解析的字符串,则应该使用 call(yourCommandString, shell=True)


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

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

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