Can i access the variables of the python script after run that python script with console? - python-3.x

I run the python script using terminal command
python3 myScript.py
It's simply run my program but if i want to open python console after complete run of my script so that i can access my script's variables.
So, What should i do ? and How can i get my script's variables after run the code using terminal ?

Open a python terminal (type 'python' in cmd);
Paste this (replace 'myScript.py' with your script filename):
def run():
t = ""
with open('myScript.py') as f:
t = f.read()
return t
Type exec(run()). Now you will have access to the variables defined in myScript.py.
I needed to do this so I could explore the result of a request from the requests library, without having to paste the code to make the requests every time.

Make the program run the other program you want with the variables as arguments. For example:
#program1
var1=7
var2="hi"
import os
os.system("python %s %d %s" % (filename, var1, var2))
#program2
import sys
#do something such as:
print(sys.argv[1]) #for var1
print(sys.argv[2]) #for var2
Basically, you are running program2 with arguments that can be referenced later.
Hope this helps :)

Related

how to repeatedly send argv inputs to an running .exe in python

Suppose I run a .exe program within python whatever os or subprocess, the .exe program is designed to pop up some different results with different arguments, my steps are the following:
In python run .exe first(keep it alive, it will have communication
with hardware and do initialization)
send different arguments to
this .exe and collect the different outputs.
I tried the following code:
hello.py
import sys
for arg in sys.argv:
print(arg)
print("Hello World!")
test.py
import subprocess
command='./exe_example/output/hello/hello.exe a b'.split()
result = subprocess.run(command, stdout=subprocess.PIPE, text=True)
print(result.stdout)
the output is:
a b Hello World!
but how to change the input argv and get the result without running the whole .exe command again?
UPDATES:
I changed the hello.py as follows:
import sys
while True:
a = input()
print('response = ',a)
after compiling to .exe, I could manually run it in the dos window
hello.exe
a
response = a
b
response = b
c
response = c
but I still don't know how to run it in python
finally, I figured out, first from this post, I added flush()
cmd = "E:/exe_example/TestCl.exe"
p = Popen(cmd, stdin=PIPE,stdout=PIPE, bufsize=0)
p.stdin.write('getall\n'.encode())
p.stdin.flush()
for i in range(48):
print(p.stdout.readline())
then, very important, if I use read(), because the .exe is always listening to the input, so it will hang up forever and never output, in this case, readline() is very important

Python script does not print output as supposed

I have a very simple (test) code which I'm running either from a Linux shell, or in interactive mode, and I have two different behaviours I cannot figure out the reason of.
I have a file generated by a Popen call, previously, where each line is a file path. This is the code used to generate the file:
with open('find.txt','w') as f:
find = subprocess.Popen(["find",".","-name","myfile.out"],stdout=f)
(Incidentally, I was trying to build a PIPE originally, namely inputting the output of this command to a grep command, and since I wasn't successful in any way, I decided to break the problem down and just read the file paths from a file, and process them one by one. So maybe there is a common issue that is blocking me somewhere in this procedure).
Since in this second step I wasn't even able to open and process the files by opening the addresses contained in each line of the find.txt file, I just tried to print the file lines out, because for sure they're available in there:
with open('find.txt','r') as g:
for l in g.readlines():
print(l)
Now, the interesting part:
if I paste the lines above into a python shell, everything works fine and I get my outputs as expected
if, on the other hand, I try to run python test.py, where test.py is the name of the file containing the lines above, no output appears in the shell's stdout.
I've tried sys.stdout.flush() to no avail. I've also inserted some dummy print() statements along the way: everything gets printed but what's after the g.readlines() statement.
Here's the full script I'm trying to make work (a pre-precursor of what I'm actually after, tbh).
#!/usr/bin/env python3
import subprocess
import sys
with open('find.txt','w') as f:
find = subprocess.Popen(["find",".","-name","myfile.out"],stdout=f)
print('hello')
with open('find.txt','r') as g:
print('hello?')
for l in g.readlines():
print('help me!')
print(l)
sys.stdout.flush()
output being:
{ancis:>106> python test.py
hello
hello?
{ancis:>106>
EDIT
I've quickly tried the very same lines (but without the call to find, which isn't available) on my python installation in Windows: it works as expected)
Based on that, I've tried to run the simpler code below:
print('hello')
with open('find.txt','r') as g:
print('hello?')
for l in g.readlines():
print('help me!')
print(l)
sys.stdout.flush()
as a script, in Linux - This also works w/o problems.
This should mean that somehow I'm messing things up with the call to Popen... But what?
This is a race condition.
Your call to
find = subprocess.Popen(["find",".","-name","myfile.out"],stdout=f)
is opening another process and running your find command which takes a bit of time to fully execute.
Python then continues on and reaches the reading of the file portion before the command is fully executed and the file is generated.
Want to test it out?
Add a time.sleep(1) just before the opening of the file.
Full test script:
#!/usr/bin/env python3
import subprocess
import time
with open('find.txt','w') as f:
find = subprocess.Popen(["find",".","-name","myfile.out"],stdout=f)
time.sleep(1)
with open('find.txt','r') as g:
for l in g:
print(l)
To block until the process is complete you can use find.communicate().
With this you can also optionally set a timeout if that's something that you want.
#!/usr/bin/env python3
import subprocess
with open('find.txt','w') as f:
find = subprocess.Popen(["find",".","-name","myfile.out"],stdout=f)
find.communicate()
with open('find.txt','r') as g:
for l in g:
print(l)
Source:
https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate

How to run a python function from Windows 10 command prompt in 'python filename.py funcname' format?

I have the following python file, named hello.py:
print('Hello')
def world():
print('Hello World')
If I type the following within the command prompt for windows 10 I get:
In: python hello.py
Out: 'Hello'
In: python hello.py world
Out: 'Hello'
Notice in the second command prompt, 'Hello World' is not an output. Any reason on why my file can't execute the python function when called in the command line but is able to load the file no problem?
Why do I need this?: I need to submit a larger file that has many functions for a project. For this file to be automatically graded I need to be able to call any given function from it using the specific sequence 'python filename.py functionname.'
Update: Some of the answers below do work, but they do not follow the specific sequence of 'python filename.py functionname' required for my project to be graded. I appreciate the insights that everyone has provided so far.
You can run functions directly from the command prompt by using:
python -c 'from hello import world; world()'
You can run the python interpreter as an alternative. cd to your file directory and launch python:
python
and then import the function from your file:
from hello import world
(Launching the python cmd from the same directory as your file.)
Then, you can run:
>>> world()
Hello World
Try this piece of code and type hello.py only:
print('Hello')
def world():
return'Hello World'
world()
##################################################################
def F1():
print('This is the first function.')
if __name__ == '__main__':
F1()
def F2():
print('This is the second function.')
if __name__ == '__main__':
F2()
now you can use form(file_name) import(function_name) create folder(1) with multiple functions in it and you can try to import the desired function into another folder(2) one at a time not all of them all at once by using this.
pardon me for the mistakes if found any feel free to ask further if this does not elaborate.
I found a solution that works for me:
After digging deeper, I realized that windows passes a sys.argv input that contains a string of all the command prompt inputs used to call the file.
In my case of 'python hello.py world', the system would pass ['hello.py','world'] as the argument for sys.argv. By creating a dictionary of callable functions, and then matching the string of the sys.argv with its respective function in the dictionary, I am able to execute the code as desired.
New code:
print('Hello')
def world():
print('Hello World')
import sys
callable_functions = {'world':world}
callable_functions[sys.argv[1]]()
Command prompt input and output now:
In: python hello.py world
Out: 'Hello'
Out: 'Hello World'

Python 3 does not recognize special characters

This is the app.py file.
#!/usr/bin/python3
import sys
def run():
print(sys.argv)
filename = sys.argv[1]
print(filename)
return
if __name__ == '__main__':
run()
I want to run this code from the command line, so I tried the two following lines each.
python3 app.py input.txt
python3 app.py < input.txt
The first command showed the result I expected, which is ['app.py', 'input.txt']. However the second command just ended up showing ['app.py'].
It seems like the Python code does not recognize the special symbols. How can I make the script recognize them without changing the script itself? i.e. not modifying the command like this: python3 app.py '<' input.txt.
The < character is special and will actually stream the file specified to stdin. You cannot override this behavior as it comes from your shell not python itself. Here is an example of what is really happening, and how you can get the file contents.
import sys
file_contents = sys.stdin.read() # This will read the entire stdin stream into file_contents
This will also work for the | character
echo "Hello, World" | python app.py

Testing python programs without using python shell

I would like to easily test my python programs without constantly using the python shell since each time the program is modified you have to quit, re-enter the python shell and import the program again. I am using a 2012 Macbook pro with OSX. I have the following code:
import sys
def read_strings(filename):
with open(filename) as file:
return file.read().split('>')[1:0]
file1 = sys.argv[1]
filename = read_strings(file1)
Essentially I would like to read into and split a txt file containing:
id1>id2>id3>id4
I am entering this into my command line:
pal-nat184-102-127:python_stuff ceb$ python3 program.py string.txt
However when I try the sys.argv approach on the command line my program returns nothing. Is this a good approach to testing code, could anyone point me in the correct direction?
This is what I would like to happen:
pal-nat184-102-127:python_stuff ceb$ python3 program.py string.txt
['id1', 'id2', 'id3', 'id4']
Let's take this a piece at a time:
However when I try the sys.argv approach on the command line my
program returns nothing
The final result of your program is that it writes a string into the variable filename. It's a little strange to have a program "return" a value. Generally, you want a program to print it's something out or save something to a file. I'm guessing it would ease your debugging if you modified your program by adding,
print (filename)
at the end: you'd be able to see the result of your program.
could anyone point me in the correct direction?
One other debugging note: It can be useful to write your .py files so that they can be run both independently at the command line or in a python shell. How you've currently structured your code, this will work semi-poorly. (Starting a shell and then importing your file will cause an error because sys.argv[1] isn't defined.)
A solution to this is to change your the bottom section of your code as follows:
if __name__ == '__main__':
file1 = sys.argv[1]
filename = read_strings(file1)
The if guard at the top says, "If running as a standalone script, then run what's below me. If you imported me from some place else, then do not execute what's below me."
Feel free to follow up below if I misinterpreted your question.
You never do anything with the result of read_strings. Try:
print(read_strings(file1))

Resources