Python: Django: How to run django app using a python script - python

I've a python file named "config.py" which actually checks the ip of user and run the django server on that port accordingly. The method I used there was to create a batch file using python and execute it later.
import socket
import subprocess
x = socket.gethostbyname(socket.gethostname())
x = str(x)
with open("run.bat", "w") as f:
f.write(f'manage.py runserver {x}:0027')
subprocess.call([r'run.bat'])
But this method is not very effective. I want a way like:
import something
something.run("manage.py")
or something accordingly
Kindly Help me doing this
Edit:
I've seen Django's manage.py.
Can I edit this file (the sys.argv section) in such a way that it automatically runs a server on 192.168.x.x:8000 just by clicking on manage.py?
Please help

I think the method you're trying to reach is to run a shell command inside a python script, which can be achieved by using the os.system() function.
You can use it in your code as the following:
import socket
import subprocess
import os
x = socket.gethostbyname(socket.gethostname())
x = str(x)
os.system(f'manage.py runserver {x}:0027')

Related

Sagemath as daemon service - name 'e' is not defined"

I have been using Sagemath as a daemon service following the Python code presented here:
https://ask.sagemath.org/question/23431/running-sage-from-other-languages-with-higher-performance/
That code sets up Sagemath as a daemon service using python sockets
I make sockets calls via php sockets to connect with this sagemath daemon, and it works fine, except that it does not recognize the constant 'e', while it does recognize 'pi'.
For example, if I run simplify(4*pi^2*pi^3) through the socket call, it will do the algebra correctly, whereas if I run simplify(4*pi^2*pi^3*e), it returns the error:
ERROR: <class 'NameError'> name 'e' is not defined
From what I have gathered, when run this way Sagemath will need to import libraries explicitly. The imports in the python daemon are:
import sys
from io import StringIO
from sage.all import *
from sage.calculus.predefined import x
from sage.repl.preparse import preparse
A temporary workaround is using exp(1) for the e.

Why am I getting a 500 Internal Server Error when importing local python file?

I've set up a local apache2 web server on my Mac. I have a button that calls a javascript function onclick. That javascript function uses JQuery .ajax to call a local python file currently named test.py (shown below). In test.py I am trying to import another local module from a python file i've named frontEndSupport.py to use a function called create_graph.
The problem is: when I click the button on my webpage that triggers all of this, I ultimately get a 500 server error.
Here is the code in test.py:
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
#from frontEndSupport import create_graph
import datetime
print "Content-type: text\n\n";
# Create instance of FieldStorage
data= cgi.FieldStorage()
# Get data from fields
ticker = data.getvalue("ticker")
day = data.getvalue("day")
print("Ticker: {0}".format(ticker))
print("Day: {0}".format(day))
#ticker = "CSCO"
#day = datetime.datetime(2021, 2, 10, 14, 30, 0).strftime("%Y-%m-%d %H:%M:%S")
#create_graph(ticker, day)
As it is right now, with the import from frontEndSupport commented out, it works fine. In the javascript function I create an alert with the ajax response and it gives the proper alert (Ticker: ... Day: ...) so I know that the environment is set up correctly to access and run this python script.
However when I uncomment "from frontEndSupport import create_graph" I get a 500 internal server error when clicking the button, even if I don't use create_graph so I believe simply importing this module is the problem. I have ran test.py using create_graph from the command line with hardcoded variables instead of using cgi and it works as expected.
As I said I think the problem is the import. It may have something to do with the server not knowing where the file is, but I don't know what to do to fix that (if that is the case).
Hopefully that background information was straight forward but I can clarify or provide more information if needed.
I figured out the problem. I was getting a 500 internal server error from a problem during python interpretation. Inside of frontEndSupport.py there are imports to packages installed with pip that are managed in the path to python3. My shebang needed to be #!/anaconda3/bin/python3.

running a .py file from another Python script using os

Can someone give me a tip on how I can use os to run a different .py file from my python script? This code below works, but only because I specify the complete file path.
How can I modify the code to incorporate running plots.py from the same directory as my main script app.py? Im using Windows at the moment but hoping it can work on any operating system. Thanks
import os
os.system('py C:/Users/benb/Desktop/flaskEconServer/plots.py')
You can execute an arbitrary Python script as a separate process using the subprocess.run() function something like this:
import os
import subprocess
import sys
#py_filepath = 'C:/Users/benb/Desktop/flaskEconServer/plots.py'
py_filepath = 'plots_test.py'
args = '"%s" "%s" "%s"' % (sys.executable, # command
py_filepath, # argv[0]
os.path.basename(py_filepath)) # argv[1]
proc = subprocess.run(args)
print('returncode:', proc.returncode)
If you would like to communicate with the process while it's running, that can also be done, plus there are other subprocess functions, including the lower-level but very general subprocess.Popen class that support doing those kind of things.
Python has built-in support for executing other scripts, without the need for the os module.
Try:
from . import plots
If you want to execute it in an independent python process, look into the multiprocessing or subprocess modules.
You can get the directory of the app.py file by using the following call in app.py
dir_path = os.path.dirname(os.path.realpath(__file__))
then join the file name you want
file_path = os.path.join(dir_path,'plot.py')
Finally your system call
os.system(f'py {file_path}') # if you're on 3.6 and above.
os.system('py %s' % file_path) # 3.5 and below
As others have said sub-processes and multi-threading may be better, but for your specific question this is what you want.

How can I import a python file through a command prompt?

I am working on project euler and wanted to time all of my code. What I have is directory of files in the form 'problemxxx.py' where xxx is the problem number. Each of these files has a main() function that returns the answer. So I have created a file called run.py, located in the same directory as the problem files. I am able to get the name of the file through command prompt. But when I try to import the problem file, I continue to get ImportError: No module named problem. Below is the code for run.py so far, along with the command prompt used.
# run.py
import sys
problem = sys.argv[1]
import problem # I have also tired 'from problem import main' w/ same result
# will add timeit functions later, but trying to get this to run first
problem.main()
The command prompts that I have tried are the following: (both of which give the ImportError stated above)
python run.py problem001
python run.py problem001.py
How can I import the function main() from the file problem001.py? Does importing not work with the file name stored as a variable? Is there a better solution than trying to get the file name through command prompt? Let me know if I need to add more information, and thank you for any help!
You can do this by using the __import__() function.
# run.py
import sys
problem = __import__(sys.argv[1], fromlist=["main"]) # I have also tired 'from problem import main' w/ same result
problem.main()
Then if you have problem001.py like this:
def main():
print "In sub_main"
Calling python run.py problem001 prints:
In sub_main
A cleaner way to do this (instead of the __import__ way) is to use the importlib module. Your run.py needs to changes:
import importlib
problem = importlib.import_module(sys.argv[1])
Alternatives are mentioned in this question.
For sure! You can use __ import_ built-in function like __import__(problem). However this is not recommended to use, because it is not nice in terms of coding-style. I think if you are using this for testing purposes then you should use unittest module, either way try to avoid these constructions.
Regards
You can use exec() trick:
import sys
problem = sys.argv[1]
exec('import %s' % problem)
exec('%s.main()' % problem)

Call a python script in a python script

I am trying to call a python script in another python script. The directories are different. I tried
import subprocess
subprocess.call("C:\temp\hello2.py", shell=True)
But got nothing. It does not work. I reviewed many forums, but all of them are about calling it when both scripts are on the same directory.
I tried having both scripts in the same directory. In this case, I can run the model in the Python.exe (through cmd window) but not in IDLE. In IDLE, I do not even get an error message.
I really need to do that, such that I can't define the other script as a different module, etc. I need to call a script in another script.
Escape backslash (\)
"C:\\temp\\hello2.py"
or use raw string
r"C:\temp\hello2.py"
>>> print "C:\temp\hello2.py"
C: emp\hello2.py
>>> print "C:\\temp\\hello2.py"
C:\temp\hello2.py
>>> print r"C:\temp\hello2.py"
C:\temp\hello2.py
First the backslash thing, and second you should always call python scripts with the python interpreter. You never know what are *.py files associated with. So:
import sys
import subprocess
subprocess.call([sys.executable, 'C:\\temp\\hello2.py'], shell=True)
I'm not sure what you mean by 'I can't define the other script as a different module, etc. I need to call a script in another script.', but I think you can avoid the whole subprocess business by just importing your other python script, as in this answer.
i.e.
import imp
hello2 = imp.load_source("hello2", 'C:\temp\hello2.py')
That should run your hello2.py script - sorry if I'm misunderstanding the constraints of your situation.
I think we can go for an approach by altering the sys.path list.
import sys
sys.path.append("C:\\temp\\")
import hello2

Categories

Resources