如何高效地构建一个用于从命令行分阶段运行的Python脚本?

huangapple go评论65阅读模式
英文:

How to efficiently structure a python script intended to be run in parts from the command line?

问题

Here's the translated code portion without any additional content:

假设我有如下脚本

```python
import argparse

def set_up():
    
    # 需要一段时间才能运行的代码
    
    initial_number = 5
    
    return initial_number

def add_n(initial_number, n):
    
    # 不需要太长时间的代码
    
    result = initial_number + n
    
    return result

if __name__ == "__main__":
    
    parser = argparse.ArgumentParser()
    parser.add_argument("n", help="要添加的数字")
    args = parser.parse_args()
    
    n = int(args.n)
    
    initial_number = set_up()
    
    result = add_n(initial_number, n)
    
    print(result)

这个脚本的思想是可以通过命令行运行,例如:

python foo.py 3

会返回 8。到目前为止一切正常。我的问题是,我希望能够在之后再次调用脚本(例如,python foo.py 1 返回 6而不需要重新运行 set_up 方法。

在这个示例中可能无关紧要,但是对于我的需求来说,set_up 方法需要运行相当长的时间。我想要的是只运行一次设置,然后多次运行 add_n 方法。这种做法是否可能?如果可能,如何实现?否则,是否有其他方法满足这种需求?我应该如何重新思考这个过程?最终的问题是如何构建一个在开头有重载阶段的脚本,该阶段只执行一次。


<details>
<summary>英文:</summary>

Suppose I have a script like so:

import argparse

def set_up():

# Code that takes a while to run

initial_number = 5

return initial_number

def add_n(initial_number, n):

# Code that doesn&#39;t take so long 

result = initial_number + n

return result

if name == "main":

parser = argparse.ArgumentParser()
parser.add_argument(&quot;n&quot;, help=&quot;number to add&quot;)
args = parser.parse_args()

n = int(args.n)

initial_number = set_up()

result = add_n(initial_number, n)

print(result)

The idea is the run it from the command line using the command (for example):

`python foo.py 3` 

Which returns `8`. All good so far. My thing is that I want to be able to call the script again after (e.g., say, `python foo.py 1` to return `6`) **without re-running** the `set_up` method. 

In this illustrative example it doesn&#39;t matter, but for my purposes the `set_up` method takes quite a while to run. What I&#39;d like is to be able to run the setup only once, and then to run the `add_n` method multiple times. Is this possible? If so, how can it be done? Otherwise, is there another approach to this type of requirement? Should I be thinking about the process differently? Ultimately the question is how to structure a script that has a heavy &quot;loading&quot; phase at the beginning that is only performed once.

</details>


# 答案1
**得分**: 2

我看到两种解决方案:

1)您将设置的输出存储在某个地方,在设置函数中检查该存储的输出。如果存在,就不需要再进行繁重的计算。您可以使用json、文本文件,甚至[pickle][1]。
2)您永远不离开脚本。当用户启动脚本时,它运行设置函数,然后等待用户输入,而不离开Python代码。您可以使用“while”循环,向用户显示一些选项(例如:1)添加一个值 2)退出),并使用[input内置函数][2]读取用户输入。

附言:不回答您的问题,您可以使用[fire][3]库来替代argparse,它更用户友好且更容易使用。

  [1]: https://docs.python.org/3/library/pickle.html
  [2]: https://docs.python.org/3/library/functions.html?highlight=input#input
  [3]: https://github.com/google/python-fire

<details>
<summary>英文:</summary>

I see two solutions:

1) you store the output of the setup somewhere. and in the setup function you check for that stored output. If it exists, no need to do the heavy computation again. You can use a json, a text file or even a [pickle][1].
2) You never leave the script. When the user launches the script, it runs the set up functions and then waits for user input. without leaving the python code. You can use a &quot;while&quot; loop, show some options to the user (example: 1) add a value 2) quit) and read the user input with [input built-in function][2]   

ps: not answering your question, you can use [fire][3] library to replace argparse, it is more user friendly and easier to use.


  [1]: https://docs.python.org/3/library/pickle.html
  [2]: https://docs.python.org/3/library/functions.html?highlight=input#input
  [3]: https://github.com/google/python-fire

</details>



huangapple
  • 本文由 发表于 2023年5月10日 21:29:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76219053.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定