What is the best way to translate the following MATLAB command to Python?
[~,hostname] = system('hostname');
To give an example on Kong's explanation, you can always wrap the syscall inside a try
block like this:
import sys
import errno
try:
hostname = socket.gethostname()
except socket.error as s_err:
print >> sys.stderr, ("error: gethostname: error %d (%s): %s" %
(s_err.errno, errno.errorcode[s_err.errno],
s_err.strerror))
This will format the error information as something like error: gethostname: error 13 (EACCES): Permission denied
, although this is just a hypothetical situation.
If you want to use an external process in the way system()
does (but without spawning a shell), you can execute a command using subprocess
:
import subprocess
cmd = subprocess.Popen(["hostname"], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
cmdout, cmderr = cmd.communicate()
print "Command exited with code %d" % cmd.returncode
print "Command output: %s" % cmdout