如何pythonsubprocess.check_输出mac os上的linux命令

2024-09-27 22:26:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过python2.7在maxosx10.11.6上运行一个linux可执行文件

我想用subprocess.check_输出. 在

通过终端工作的命令是:

mosel -c "exec PATH/TO/SCRIPT arg1='value1', arg2='value2'"

但是,当我尝试:

^{pr2}$

在哪里

cmd="exec PATH/TO/SCRIPT arg1='value1', arg2='value2'"'

我得到:

File "/usr/local/lib/python2.7/site-packages/subprocess32.py", line 629, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/local/lib/python2.7/site-packages/subprocess32.py", line 825, in __init__
restore_signals, start_new_session)
File "/usr/local/lib/python2.7/site-packages/subprocess32.py", line 1574, in _execute_child
raise child_exception_type(errno_num, err_msg)
OSError: [Errno 2] No such file or directory: 'mosel'

我已经能够让它将命令“回显”到输出文件,但是我不能通过python运行“which mosel”,这使我相信它与check_输出有关,使用“bin/sh”作为可执行文件。在

那么,我需要用“Popen”代替set吗

executable=path/to/mosel

是吗?在

如果是这样,如何使用Python获取用户到mosel的路径(即获取“which mosel”的输出)?在

谢谢!在

更新:

PyCharm没有看到系统路径,我用这个答案修复了这个问题: Setting environment variables in OS X?

现在看来

^{pr2}$

正在将方括号发送到命令行,因为它现在返回:

dyld: Library not loaded: libxprm_mc.dylib
Referenced from: /usr/local/opt/xpress/bin/mosel
Reason: image not found
Traceback (most recent call last):
File "/Users/nlaws/projects/sunlamp/sunlamp-ss/RunScenarios/run.py", line 70, in <module>
run(1)
File "/Users/nlaws/projects/sunlamp/sunlamp-ss/RunScenarios/run.py", line 44, in run
out = check_output(['mosel', '-c', cmd])
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 219, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['mosel', '-c', cmd]' returned non-zero exit status -5

还是有路径问题?!(我可以通过mac终端运行mosel -c cmd,但不能通过python在pycharm中运行,也不能通过python在mac终端中运行)。在


Tags: runinpycmd终端outputlibusr
2条回答

问题的根源是DYLD_LIBRARY_PATH

The new OS X release 10.11 "El Capitan" has a "security" feature that prevents passing DYLD_LIBRARY_PATH to child processes. Somehow, that variable is stripped from the environment. - (quoted from https://www.postgresql.org/message-id/20151103113612.GW11897@awork2.anarazel.de)

安全特性称为SIP或“系统完整性保护”。不幸的是,似乎没有人能想出解决这个问题的办法(除了必须针对每一种情况的变通办法)。在

这是这个问题的另一个例子: https://github.com/soumith/cudnn.torch/issues/111

谷歌“macos inherit dyld_library_path”,你会发现许多其他的例子。在

问题是您错误地使用了check_output的参数。除非您传递它shell=Truecheck_outputexpects a list of parameters as its input,格式如下: check_call(['binary_name','arg1','arg2','arg3', ....])

因此,在这种情况下,您应该:

subprocess.check_call(['mosel', '-c', "exec PATH/TO/SCRIPT arg1='value1', arg2='value2'"])

相关问题 更多 >

    热门问题