Python Subprocess Call with variables [duplicate]

2019-05-10 10:12发布

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条回答
\"骚年 ilove
2楼-- · 2019-05-10 11:03

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])
查看更多
登录 后发表回答