简体   繁体   English

如何从脚本中给出 python 解释器命令?

[英]How can you give the python interpreter commands from within a script?

I wrote a bash script to create a setup file using echo '...' > setup.py and then in the next line I execute it using python setup.py build_ext --inplace .我编写了一个 bash 脚本来使用echo '...' > setup.py创建一个设置文件,然后在下一行中我使用python setup.py build_ext --inplace执行它。 I replicated the first part with the write method of file objects in Python, my question is how can I replicate the second part in my Python script?我用 Python 中文件对象的写入方法复制了第一部分,我的问题是如何在 Python 脚本中复制第二部分?

What it seems like you're trying to do is not to give the Python interpreter commands, but actually to execute bash/shell commands from within a Python program execution.您似乎要做的不是给出 Python 解释器命令,而是实际上从 Python 程序执行中执行 bash/shell 命令。

When you open a terminal and run:当您打开终端并运行时:

python setup.py build_ext --inplace

What happens is that a new Python process starts up and executes setup.py发生的情况是一个新的 Python 进程启动并执行 setup.py

Your goal is to do the same thing from a Python script.您的目标是从 Python 脚本中执行相同的操作。 The generally accepted way to do this is to use the subprocess module: https://docs.python.org/3/library/subprocess.html普遍接受的方法是使用subprocess进程模块: https://docs.python.org/3/library/subprocess.html

Something like就像是

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

should work.应该管用。 Or if you really know what you're doing and you know that the input to the subprocess.run call won't ever get exposed to users (and thus hijacked) you could instead use:或者,如果您真的知道自己在做什么,并且知道subprocess.run调用的输入永远不会暴露给用户(因此被劫持),您可以改用:

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

EDIT:编辑:

Alternatively if you want to dig deep into Python you could go look at how to call setuptools' build_ext command directly from code.或者,如果您想深入了解 Python 您可以 go 查看如何直接从代码调用 setuptools 的 build_ext 命令。 Here's a good start in that direction.这是朝着这个方向发展的良好开端。 https://github.com/pypa/setuptools/blob/master/setuptools/command/build_ext.py#L83 https://github.com/pypa/setuptools/blob/master/setuptools/command/build_ext.py#L83

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM