Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - how do I call external python programs?

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.

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.

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.

like image 949
Henry Edward Quinn IV Avatar asked Feb 16 '12 20:02

Henry Edward Quinn IV


People also ask

Can you call one Python script from another?

The first line of 'import python_2' in the python_1 script, would call the second python_2 script. Whenever you want to run one Python script from another, you'll need to import the exact name of the Python script that you'd like to call.

How do I import an external file into Python?

you can put the code into the same directory (ie folder) as your code. Then all you need to do is say import beautifulsoup before you try to use it. you can put the code somewhere in the python load path.


1 Answers

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() 

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

like image 78
David Robinson Avatar answered Sep 21 '22 13:09

David Robinson