将以下MATLAB命令转换为Python的最佳方法是什么?

[~,hostname] = system('hostname');

最佳答案

为了给出关于Kong的解释的示例,您始终可以将syscall包裹在try块中,如下所示:

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


尽管这只是一种假设情况,但会将错误信息格式化为类似error: gethostname: error 13 (EACCES): Permission denied的格式。



如果要使用system()的方式使用外部进程(但不生成外壳),则可以使用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

关于python - 从MATLAB到Python的System('hostname'),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29611918/

10-12 07:36
查看更多