How to call a python routine from another python routine? - python

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)

Related

Is there a function for reading in json files as dicts where you only need to provide a filepath as input?

I'm sick of doing
with open('my.json','r') as inf:
my_dict = json.load(inf)
each time I want to get the contents of a json file as a dict in python. It seems so trivial to simply add a function that just accepts 'my.json' as a path and then implicitly opens the file and then loads the json file with whatever additional keywords you want. I found the pandas.read_json() class, but if I tried that it gave me the same error that I get if I try to call json.load() on a filepath. Is it difficult to add my custon reading function to the json package? How do I add a function to a package that is easily callable from any script with an import statement, so I don't have to write the same function over and over again? Is there a particular reason why this isn't an available function? Am I just lazy?
I know what the code for my solution is, I just don't know where to add it so it's easily importable and whether or not this is a very bad idea to begin with, since it would require a modification of a builtin python package.

Python 3.7 - Save and import a file holding Python variables

This seems like a pretty obvious/dumb question, but there are a few specifications that make this a bit harder.
Let's say I have a program that takes 3 numbers from a user and does mathematical processes to them to get outputs. Then I open("file", "r") to write those variables to a file.
Then, let's say another program then imports them and uses them for other processes. I need to be able to import that file as Python code. To be clear: I am not saving text, I am saving python code to a file that is not a .py file.
Is there any way to save and import Python code to and from a non-.py file? And how?
EDIT: In the file I'm saving and importing, I'm also saving Python functions. I cannot simply save the variables themselves; I need the variable names, values, and python functions to be saved as normal text in a file, but when I import the file, it should be parsed as Python code.
Probably not a good idea to store computation result as code & then import it from elsewhere. You should use a proper data format to store the results - and import it as data. Use JSON or pickle etc.
However, if you do want to shoot yourself in the foot, Python gives you the tools to do that:
Let's say i have some code in a file temp.txt
number3=30
def f():
return 'method'
Then you can do this:
with open('temp.txt') as f:
code = f.read()
exec(code)
print(number3)
print(f())
Which outputs:
30
method
If i got this right, this might be done via eval function e.g. you save all code to be executed into a string and then save into a file.
When you need that executed read the file, tke the string and eval it
I must say however that using eval is a bad (very bad) practice and i would advice against it unless there is no other solution that you can find

Python using same date/time in multiple files

I'm currently generating three different xml files, and I would like to have the second and third file have the same date/time as the first file.
In the first file, I do
import datetime
time = datetime.datetime.utcnow().strftime('%y%m%d%H%M%S')
This gives me the format I would like. I've tried multiple approaches such as storing it in a different variable and importing it to the second and third files, but it seems that it'll always keep the actual current time and not the time of the first file. I don't know if there's a solution to my problem using the datetime module but if anyone has any ideas that would be wonderful.
Whenever you call that function, whether directly or through import it will always run again and give a new "now".
If the same program just uses that string for 3 times there shouldn't be a problem, but if you're running 3 different scripts you will get 3 different dates!
To avoid this, I would save the first generated string to a file:
with open('.tmpdate') as f:
f.write(time)
And read it in the next to files:
with open('.tmpdate') as f:
time = f.read()
And finally, just to clean up after yourself, you can delete that file after it was used for the 3rd time with os.remove('.tmpdate') (you need to import os before that, of course)

How to share a variable between two python scripts run separately

I'm an extreme noob to python, so If there's a better way to do what I'm asking please let me know.
I have one file, which works with flask to create markers on a map. It has an array which stores these said markers. I'm starting the file through command prompt, and opening said file multiple times. Basically, how would one open a file multiple times, and have them share a variable (Not the same as having a subfile that shares variables with a superfile.) I'm okay with creating another file that starts the instances if needed, but I'm not sure how I'd do that.
Here is an example of what I'd like to accomplish. I have a file called, let's
say, test.py:
global number
number += 1
print(number)
I'd like it so that when I start this through command prompt (python test.py) multiple times, it'd print the following:
1
2
3
4
5
The only difference between above and what I have, is that what I have will be non-terminating and continuously running
What you seem to be looking for is some form of inter-process communication. In terms of python, each process has its own memory space and its own variables meaning that if I ran.
number += 1
print(number)
Multiple times then I would get 1,2..5 on a new line. No matter how many times I start the script, number would be a global.
There are a few ways where you can keep consistency.
Writing To A File (named pipe)
One of your scripts can have (generator.py)
import os
num = 1
try:
os.mkfifo("temp.txt")
except:
pass # In case one of your other files already started
while True:
file = open("temp.txt", "w")
file.write(num)
file.close() # Important because if you don't close the file
# The operating system will lock your file and your other scripts
# Won't have access
sleep(# seconds)
In your other scripts (consumer.py)
while True:
file = open("temp.txt", "r")
number = int(file.read())
print(number)
sleep(# seconds)
You would start 1 or so generator and as many consumers as you want. Note: this does have a race condition that can't really be avoided. When you write to the file, you should use a serializer like pickler or json to properly encode and decode your array object.
Other Ways
You can also look up how to use pipes (both named and unnamed), databases, ampq (IMHO the best way to do it but there is a learning curve and added dependencies), and if you are feeling bold use mmap.
Design Change
If you are willing to listen to a design change, Since you are making a flask application that has the variable in memory why don't you just make an endpoint to serve up your array and check the endpoint every so often?
import json # or pickle
import flask
app = Flask(__name__)
array = [objects]
converted = method_to_convert_to_array_of_dicts(array)
#app.route("/array")
def hello():
return json.dumps(array)
You will need to convert but then the web server can be hosted and your clients would just need something like
import requests
import json
while True:
result = requests.get('localhost/array')
array = json.loads(str(result.body)) # or some string form of result
sleep(...)
Your description is kind of confusing, but if I understand you correctly, one way of doing this would be to keep the value of the variable in a separate file.
When a script needs the value, read the value from the file and add one to it. If the file doesn't exist, use a default value of 1. Finally, rewrite the file with the new value.
However you said that this value would be shared among two python scripts, so you'd have to be careful that both scripts don't try to access the file at the same time.
I think you could use pickle.dump(your array, file) to serie the data(your array) intoto a file. And at next time running the script, you could just load the data back with pickle.dump(your array, file)

Create variable from unassigned text

I'm trying to set up a program to be able to read in text located the the program file but which is not assigned to a variable.
What I mean by that is:
There once was a boy who went on an adventure.
He did many, many thing. Yada, yada, yada.
[begin code here to read text]
I'm trying to design it to take in the typed lines of text and then be able to give variable names to each line until it reaches a stopping point like a blank like or a line with only a period. Assuming the text will begin on line 2.
If anybody has any ideas on how to make this work they would be very much appreciated.
Maybe if you tried smuggling the text in as a docstring?
"""Test Doc String"""
print __doc__
Results in (if this code is saved in source.py):
me#Bob:~$ python source.py
Test Doc String
This relies upon keeping your program within a single file. If you import that file (e.g. from source.py to target.py) you would then have to refer to that docstring using the name of the source file (e.g. source.doc). Anyway, you can assign doc to the variable of your choice and then parse away...
But do you really want to do this? Why not read the text in from a separate text file?

Categories