Python-如何调用外部python程序? [英] Python - how do I call external python programs?

查看:179
本文介绍了Python-如何调用外部python程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将以说这是一项家庭作业作为开头.我不想为我写代码,只是要指出正确的方向.

I'll preface this by saying it's a homework assignment. I don't want code written out for me, just to be pointed in the right direction.

我们能够选择一个项目,所以我正在开发一个程序,以作为到目前为止我已写过的所有内容的迷你组合.因此,我将制作一个程序,用户将输入程序的名称(从给定列表中选择),然后在现有的shell中运行所选的程序.

We're able to work on a project of our choice so I'm working on a program to be a mini portfolio of everything I've written so far. So I'm going to make a program that the user will input the name of a program (chosen from a given list) and then run the chosen program within the existing shell.

但是,我真的找不到有关如何调用外部程序的信息.谁能指出我正确的方向?我考虑过将所有代码放入带有多个if循环的长程序中,以执行正确的代码,但我想使它的BIT比这更复杂.

However, I can't really find information on how to call upon external programs. Can anyone point me in the right direction? I considered putting all the code in one long program with a bunch of if loops to execute the right code, but I'd like to make it a BIT more complicated than that.

推荐答案

如果您要以Python脚本的形式调用它们,则可以这样做

If you want to call each as a Python script, you can do

import subprocess
subprocess.call(["python", "myscript.py"])
subprocess.call(["python", "myscript2.py"])

但是更好的方法是调用您用其他脚本编写的函数,如下所示:

But a better way is to call functions you've written in other scripts, like this:

import myscript
import myscript2

myscript.function_from_script1()
myscript2.function_from_script2()

在myscript.py和myscript2.py文件中定义了function_from_script1()等的位置.有关更多信息,请参见模块上的页面.

Where function_from_script1() etc are defined in the myscript.py and myscript2.py files. See this page on modules for more information.

这篇关于Python-如何调用外部python程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆