【问题标题】:How can you give the python interpreter commands from within a script?如何从脚本中给出 python 解释器命令?
【发布时间】:2020-10-26 02:23:34
【问题描述】:

我写了一个 bash 脚本来创建一个安装文件 echo '...' > setup.py 然后在下一行我使用python setup.py build_ext --inplace 执行它。我用 Python 中文件对象的 write 方法复制了第一部分,我的问题是如何在我的 Python 脚本中复制第二部分?

【问题讨论】:

  • 为什么不能直接在脚本中运行代码,而不是通过管道将其传送到另一个文件中?

标签: python bash shell scripting


【解决方案1】:

看起来您要做的不是给 Python 解释器命令,而是实际上是在 Python 程序执行中执行 bash/shell 命令。

当你打开终端并运行时:

python setup.py build_ext --inplace

会发生什么是一个新的 Python 进程启动并执行 setup.py

您的目标是通过 Python 脚本执行相同的操作。普遍接受的方法是使用subprocess 模块:https://docs.python.org/3/library/subprocess.html

类似

subprocess.run(["python", "setup.py", "build_ext", "--inplace"])

应该可以。或者,如果您真的知道自己在做什么,并且知道 subprocess.run 调用的输入永远不会暴露给用户(因此被劫持),您可以改用:

subprocess.run("python setup.py build_ext --inplace", shell=True)

编辑:

或者,如果您想深入研究 Python,您可以查看如何直接从代码中调用 setuptools 的 build_ext 命令。这是朝着这个方向发展的良好开端。 https://github.com/pypa/setuptools/blob/master/setuptools/command/build_ext.py#L83

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多