简体   繁体   中英

How to call a python routine from another python routine?

html is just text, often very repetitive. I have a simple homework webpage. I'm trying to automate the webpage production.

I have Python routines for producing html (I made them, so they are primitive, but they all work):

makeCheckboxes.py  
makeDropdownboxes.py  
makehtmlTable.py  
makeRadiobuttons.py  
makeTextboxes.py  
makeThankyouPHP.py  

and lastly:

makeWebpage.py

They all just output a text file.

Rather than lump all these in one very big, long file (I lose the plot easily), I'd like to call the one or ones I want from makeWebpage.py and run it, then knot the sections together into 1 text file.

They are all in /home/pedro/textTohtml/ I run them in a bash terminal.

I don't need all the routines each week.
All I need to know is, how many sections I want and what's in it.

For example, let's say next week: Section 1 is radio buttons, Section 2 is Textboxes (fill in the gaps exercise)

Can I call the 2 routines from makeWebpage.py without actually defining them within as functions?

The functions themselves produce a text file which I can then open and integrate into the webpage template.

EDIT: Thanks for the answers. What I need is to import the whole file, each of which will then have its own inner functions. If I do this:

import file as fl

Will it then run fl? Or is it better to run subprocess?

How does this help you:

Call a function from another file in Python

You just need to use

from file import function

To import the functions at the start of your makeWebpage.py file. Then makeWebpage.py can call any of the functions any time it wants.

If you only need a function:

from FILE import FUNCTION
FUNCTION(*args,**kwargs)

If you want to run/execute the python file (everything):

import os
os.system("FILE")

[NOTE] The file must be a string and contain the extension, eg "some_file.py" whereas in import statements only the file name is specified in plaintext.

In both cases both files must be in the same directory unless a path is specified ( "c:\\Users\\MyProfile\\PythonFiles\\python.py" or "/Users/MyProfile/PythonFiles\\python.py" )

EDIT: If you are importing an entire file (STRICTLY LIKE THIS!) from FILE import * you can name variables or functions with an underscore before it to prevent it from being imported (more info on PEP 8 https://www.python.org/dev/peps/pep-0008/#id36 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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