简体   繁体   English

在终端中导入Python库

[英]Import Python library in terminal

I need to run a Python script in a terminal, several times. 我需要在终端中多次运行Python脚本 This script requires me to import some libraries. 此脚本要求我导入一些库。 So every time I call the script in the terminal, the libraries are loaded again, which results in a loss of time. 因此,每次我在终端中调用脚本时,都会再次加载库,这会浪费时间。 Is there any way I can import the libraries once and for all at the beginning? 一开始我有什么办法可以一劳永逸地导入库吗? (If I try the "naive" way, calling first a script just to import libraries then running my code, it doesn't work). (如果我尝试“天真”的方式,首先调用一个脚本只是为了导入库,然后运行我的代码,则它将不起作用)。

EDIT: I need to run the script in a terminal because actually it is made to serve in another program developed in Java. 编辑:我需要在终端中运行该脚本,因为实际上它是在Java开发的另一个程序中提供的。 The Java code calls the Pythin script in the terminal, reads its result and processes it, then calls it again. Java代码在终端中调用Pythin脚本,读取其结果并进行处理,然后再次调用它。

The libraries will be unloaded once the script finishes, so the best way you can handle this is to write the script so it can iterate however many times you want, rather than running the whole script multiple times. 脚本完成后,库将被卸载,因此处理此问题的最佳方法是编写脚本,以便脚本可以进行任意多次迭代,而不是多次运行整个脚本。 I would likely use input() (or raw_input() if you're running Python2) to read in however many times you want to iterate over it, or use a library like click to create a command line argument for it. 我可能会使用input()(或者如果运行Python2,则使用raw_input())进行多次读操作,或者使用诸如click这样的库来为其创建命令行参数。

One solution is that you can leave the python script always running and use a pipe to communicate between processes like the code below taken from this answer. 一个解决方案是,你可以离开python脚本始终运行和使用的管道像从下面拍摄的码进程间通信这个答案。

import os, time

pipe_path = "/tmp/mypipe"
if not os.path.exists(pipe_path):
    os.mkfifo(pipe_path)
# Open the fifo. We need to open in non-blocking mode or it will stalls until
# someone opens it for writting
pipe_fd = os.open(pipe_path, os.O_RDONLY | os.O_NONBLOCK)
with os.fdopen(pipe_fd) as pipe:
    while True:
        message = pipe.read()
        if message:
            print("Received: '%s'" % message)
        print("Doing other stuff")
        time.sleep(0.5)

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

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