Python Subprocess Call with variables [duplicate]

为君一笑 提交于 2020-01-02 08:08:26

问题


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.

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

However this does not work

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

buidling the command first with

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

also results in the same error.


回答1:


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


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


来源:https://stackoverflow.com/questions/33653525/python-subprocess-call-with-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!