【问题标题】:Python Subprocess Call with variables [duplicate]带有变量的Python子进程调用[重复]
【发布时间】:2016-02-12 17:16:25
【问题描述】:

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

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

之后我想使用 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])
  • 链接问题的答案在技术上可行,但不安全,不应使用。因此,我认为不适合将这个问题标记为重复问题,因为另一个问题已经得到回答。下面查尔斯·达菲的回答要好得多。

标签: python subprocess python-2.6


【解决方案1】:

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


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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    相关资源
    最近更新 更多