I have created a python script with a single function in it. Is there a way to call the function from the python terminal to test some arguments?
import time
import random
def string_teletyper(string):
'''Prints out each character in a string with time delay'''
for chr in string:
print(chr, end='', flush=True)
time.sleep(random.randint(1,2)/20)
If I want to test an argument for the function, I would have to add string_teletyper(argument) inside the script itself and run it, is there a faster way?
you can do,
>>> from yourfilename import *
>>> string_teletyper(arg)
import all function or specific function from the file and you don't need to put .py at the end of yourfilename when you used it as a module.
Running parts of a Python module many times during development is a common development task. The way most Python developers do this is to use the following code:
import time
import random
def string_teletyper(string):
'''Prints out each character in a string with time delay'''
for chr in string:
print(chr, end='', flush=True)
time.sleep(random.randint(1,2)/20)
if __name__ == "__main__":
test_st = 'My string to test as an argument'
string_teletyper(test_st)
This means that anything in the if block will only get ran if the module is called via $python my_file.py and not called in a module.
Related
I have a two different python programs. How can I run one program in another when I need it (e.g if a certain condition is met)?
I heard that I can do that with import <program name>, but when I do this, the program starts immediately and not when I need it.
You should wrap the code in a function. When you want to run that part of code, just call the function.
file1.py:
def fuc1():
print("run.")
# This is to run fuc1 when you run file1 using "python file1.py"
if __name__ == '__main__':
fuc1()
in file2.py:
from file1 import fuc1
fuc1() # call it when you want to run it
try making the second program into a function in that file and import the function like
from <file-name> import <function>
and call the function when the conditions are met
You can just call the import wherever you need it (not necessarily at the top of the file but in the middle of your code) and wrap it inside an if statement so the import will be called when that condition is fulfilled.
I want to import one specific line of code from one script into another. I don't want the new code to run the entire script just that one line. How do I do that?
e.g. from brcus import value
where value is equal to a number in the completed script and I want to import that number into the new script, and that line of code in the old script is: "value=500"
I would not recommend your approach for extracting a variable. You should instead have a look at actual data exchange formats e.g. json or xml.
These are designed to hold and make accessible key-value pairs for programs while being (to some extend) human readable.
Parsers for these formats and many more are available.
Whenever you import any python module or package and you use some function or value from that module it is not run all the script at once.
You can do it like that.
new script: - new.py
old script:- old.py
if it's in same directory..
from old import value
a = value
I would suggest moving the part you want to import to a separate module and importing it to all modules it's used in
my_var.py
text = "Hello"
test.py
from my_var import text
def hello_friend(friend_name)
print(text + " " + friend_name)
main.py
from my_var import text
print(text)
You may also set an environmental variable and check it's value in the module you are importing
test.py
import os
if os.environ['only_new_str'] != str(True):
print("new_str is not calculated yet")
new_str = "Hello world"
if os.environ['only_new_str'] != str(True):
print("new_str calculated")
main.py
import os
os.environ['only_new_str'] = str(True)
import test
print(test.new_str)
if you import with the command
from package import value
the value will come to your new code as being part of it
E.g
Source.py
value = 500
other = 400
Destiny.py
from Source import value
print (value)
>>500
Destiny.py
from Source import value
print (other)
>>NameError: name 'other' is not defined
I have a script a.py and while executing it will ask certain queries to user and frame the output in json format. Using python subprocess, I am able to call this script from another script named b.py. Everything is working as expected except that I am not able to get the output in a variable? I am doing this in Python 3.
To call a Python script from another one using subprocess module and to pass it some input and to get its output:
#!/usr/bin/env python3
import os
import sys
from subprocess import check_output
script_path = os.path.join(get_script_dir(), 'a.py')
output = check_output([sys.executable, script_path],
input='\n'.join(['query 1', 'query 2']),
universal_newlines=True)
where get_script_dir() function is defined here.
A more flexible alternative is to import module a and to call a function, to get the result (make sure a.py uses if __name__=="__main__" guard, to avoid running undesirable code on import):
#!/usr/bin/env python
import a # the dir with a.py should be in sys.path
result = [a.search(query) for query in ['query 1', 'query 2']]
You could use mutliprocessing to run each query in a separate process (if performing a query is CPU-intensive then it might improve time performance):
#!/usr/bin/env python
from multiprocessing import freeze_support, Pool
import a
if __name__ == "__main__":
freeze_support()
pool = Pool() # use all available CPUs
result = pool.map(a.search, ['query 1', 'query 2'])
Another way than mentioned, is by using the built-in funtion exec
This function gets a string of python code and executes it
To use it on a script file, you can simply read it as a text file, as such:
#dir is the directory of a.py
#a.py, for example, contains the variable 'x=1'
exec(open(dir+'\\a.py').read())
print(x) #outputs 1
I have an already written python script that returns an integer value. I would like to use that integer value as one of the arguments of a different python script I am working on. Is there a way to do this? I am working in terminal for mac.
This problem can be solved by importing the first script as a module in the second (documentation)
Let's say your first script is called script.py and looks like this:
def some_function():
return(1)
some_variable = 2
In your second script, you can import the first one as a module and use its functions and variables, when prepended by the module name:
import script
print script.some_function(), script.some_variable
This will print 1, 2.
Just import your script as a module into the second script. Then you can call any functions with the module prefix.
From within script 2:
import script1
#this is your function call that returns an integer
script1.script1function()
You can use:
from script1 import *
to have access to all the variables as well. But this is usually not a good idea especially if you plan to change the value of those variables.
from subprocess import (
Popen,
PIPE
)
p1 = Popen(['/path/to/python', "/path/to/your/script.py"], stdout=PIPE)
p1.stdout.read()
But your script need stdout,
That means it must print result
I cant figure out how to add my simple function to my main program file. why not ?
when i do this:
import print_text
echothis("this is text")
exit()
cant understand why people think this is such a bad question.
this doesnt work either:
print_text.echothis("this is text")
same thing happens if i type any of the answers below.
including:
from print_text import echothis
I just get this error:
from: can't read /var/mail/print_text
./blah3.py: line 3: syntax error near unexpected token `"this is text"'
./blah3.py: line 3: `print_text.echothis("this is text")'
or a variant without the /var/mail line...
*this file is named print_text.py*
#!/usr/bin/env python
import time
import random
import string
import threading
import sys
def echothis(txt):
woo=txt
stdout.write(woo)
EDIT: You're actually not having a python issue but a bash one. You're running your python script as if it were bash (hence the 'from: can't read from'), did you put #!/usr/bin/env python at the beginning of the file you're running (not print_text.py, the other one)? You could alternatively call it that way: python myfile.py and it should work.
When you import a module, it is namespaced, so if you want to use anything that is from that module, you need to call it using the proper namespace. Here, you would call you echothis function using print_text.echothis.
Alternatively, if you want to include echothis in your main namespace, you can use the from print_text import echothis syntax.
Try this:
import print_text
print_text.echothis("this is a text")