简体   繁体   English

如何从另一个python文件运行一个python文件?

[英]How to run one python file from another python file?

To start off, I am a beginner in python so I am not even sure if my question makes sense or is even possible. 首先,我是python的初学者,所以我什至不确定我的问题是否有意义或什至可行。

I have 2 python files app.py . 我有2个python文件app.py and compare.py . compare.py compare.py takes in two arguments (File paths) to run. compare.py接受两个参数(文件路径)来运行。 So for example, when I want to run it, I do python compare.py ./image1.jpg ./image2.jpg . 因此,例如,当我想运行它时,我执行python compare.py ./image1.jpg ./image2.jpg Now the return I get is some text printed to the terminal such as Comparison Done, The distance is 0.544 . 现在我得到的回报是一些打印到终端的文本,例如“ Comparison Done, The distance is 0.544

Now, I want to run this compare.py from inside app.py and get a string with whatever compare.py would usually output to the terminal. 现在,我想从app.py内部运行这个compare.py ,并获得一个带有通常会输出到终端的compare.py的字符串。 So for example: 因此,例如:

result = function('compare.py ./image1.jpg ./image2.jpg') and result will have the required string. result = function('compare.py ./image1.jpg ./image2.jpg')并且result将具有所需的字符串。 Is this possible? 这可能吗?

You can use os.popen : 您可以使用os.popen

In app.py: 在app.py中:

import os
output = os.popen('python compare.py ./image1.jpg ./image2.jpg').readlines()

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

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