Tips and Traps¶
The command-line tool of some (e.g., network) applications might be slow to authenticate. If you use pexect to automate such a command-line tool, it is best to wait for sometime after sending password using
child.sendline(passwd)
. If the authentication has ouput on both success and failure, a smart way is to wait for the success or failure message to come out.
Hands on the Python module subprocess
General Tips¶
The method
subprocess.run
is preferred over older high-level APIs (subprocess.call
,subprocess.check_call
andsubprocess.check_output
). The methodsubprocess.Popen
(which powers the high-level APIs) can be used if you need advanced controls. When running a shell command usingsubprocess.run
,Avoid using system shell (i.e., avoid using
shell=True
) for 2 reasons. First, avoid shell injection attack. Second, there is no need for you to manually escape special characters in the command.