Welcome Back,
To this miniseries! In today's post, I will be showing you how to actually execute the script! So, let's get started! BTW, if you don't know what I am talking about then go read Part 1 first to understand!
What are we making today?
Well, I thought you would ask. Today, just like I said we will be actually executing the code from the file! Excited?
But How?
Basically, we will be changing or modifying the Handler's python_open
function!
New Prerequisites
- sys(Included in the standard library)
- subprocess(Included in the standard library)
Let's Start
So, we are going to change the Handler's python_open
function such that, it executes the script passed as an argument!
First, change
print(urlreq.urlopen("pytohn://something/random/file.txt"))
to
urlArg = sys.argv[1]
urlreq.urlopen(urlArg)
this, and don't forget to add import sys
at the top!
Now, our handler will read the URL passed as an argument instead of a hardcoded input! YAY!
Next, we need to edit the Handler -
The previous code looked like this -
class PyProtoHandler(urlreq.BaseHandler):
def python_open(self, req):
fullUrl = req.get_full_url()
filePath = "".join(fullUrl.split("://")[1:])
return filePath
The new code will look like this -
class PyProtoHandler(urlreq.BaseHandler):
def python_open(self, req):
fullUrl = req.get_full_url()
filePath = "".join(fullUrl.split("://")[1:])
parsed_cmd = 'python {}'.format(filePath)
subprocess.run(parsed_cmd, shell=True)
So, what did we change here? We created a new variable named parsed_cmd
, which is a string containing a command that is executed by subprocess
in the next line. And the result of the execution is printed automatically.
And, we are done with today's code!
Lastly, Testing it!
Now we need to test our code!
We need to open our terminal(cmd or bash or whatever), locate to the directory where our code is located, run the file! So, let's do it! But remember to add a file path after the command! (depending upon your system.)
demo.py -
$ python pyProto.py D:/Programming/Python/demo.py
If this printed then the code works!
The End?
This was a short article since we just modified few parts of the code! But don't think it's over yet! Part 3 is coming soon! Hope to see you there! Also, I have changed the name of the file from protoHandler.py
to pyProto.py
. Also, there's a bonus for you, I have made a repository on my GitHub which contains code from all of my dev.to Posts, including this one! Here is the link - pybash1/devtoCode
And, Bye!!
Top comments (0)