简体   繁体   English

如何使用代码在 PyCharm 终端中运行脚本

[英]how to run a script in the PyCharm terminal using code

I want to run a script我想运行一个脚本

pythonw ./main.py

in my Pycharm terminal using code.在我的 Pycharm 终端中使用代码。 I tried to run it in the command prompt using我尝试使用在命令提示符下运行它

p = subprocess.Popen(["start", "cmd", "/k", "command"], shell = True)

but the script does not work.但脚本不起作用。 I want to run it in the terminal from code.我想从代码在终端中运行它。

What you did WILL run a command, but that command will be in a different shell, detatched from the current running shell unless you do work to connect the output of the spawned shell to the shell running in PyCharm.您所做的将运行一个命令,但该命令将在不同的 shell 中,与当前运行的 shell 分离,除非您确实将生成的 shell 的输出连接到在 PyCharm 中运行的 shell。

A betterway is to use runpy - The runpy module is part of the core library since Python 3.2.更好的方法是使用runpy - 从 Python 3.2 开始,runpy 模块是核心库的一部分。

Minimal working example:最小的工作示例:

1.py 1.py

from runpy import run_path
from pathlib import Path

print("1: start")
my_script = Path("2.py")
y = 10

d = {"y": y}
print(f"Input: y={y}")

assert my_script.exists(), f"Problem: I could not find {my_script}"
res = run_path(my_script, d)
y=res['y']

print(f"Result: y={y}")

print("1: done")

2.py 2.py

print("2: start")

if "y" not in globals():
    y = "y not Set, please run 1.py"

print(f"y={y} - making y bigger")

y *= 15

print("2: done")

If you need to use multiple processors (ie multiple concurrent Python interpreters) then you should take a look at concurrent.futures *, which can also make use of runpy and provides simple consistent and flexible access to all of runpy, threading and multiprocessing.如果您需要使用多个处理器(即多个并发 Python 解释器),那么您应该查看concurrent.futures *,它也可以使用 runpy 并提供对所有 runpy、线程和多处理的简单一致和灵活的访问。

As shown in the exmaple, above, runpy provides the advantage that you can directly alter and access the sub-program input and output as true Python objects from and to the parent program without resorting text processing STDIO printed or screen scraped data.如上面的示例所示,runpy 提供的优势是您可以直接更改和访问子程序输入和输出作为真正的 Python 对象进出父程序,而无需借助文本处理 STDIO 打印或屏幕抓取的数据。

* See a working toy example of concurrent.futures working with runpy in this gist * 请参阅本要点中与 runpy 一起使用的 concurrent.futures 的工作玩具示例

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

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