The first python program called first.py includes the following code:
print ('my name is viena')
How can I input the result from that first program, i.e., 'my name is viena' as input into my second program called second.py which includes the following code:
question = 'what\'s your name?'
answer = ?????HERE HOW TO INPUT THE RESULT FROM FIRST PROGRAM
print (answer)
my name is viena
Note: There should be two different python script files as I mentioned in the question.
If you can wrap the print statement in your first program inside a function (say print_name) , then you can so something like
import first
first.print_name()
to get the name.
For a completely general purpose solution that involves shelling out, take a look at the subprocess module.
How about change the first script as importable module:
# Changed the print function call with function.
def my_name():
return 'my name is viena'
if __name__ == '__main__':
print(my_name())
Another script can now import the first script using import statement, and use its functions.
import name_of_the_first_script
question = "what's your name?"
answer = name_of_the_first_script.my_name()
Related
I'm trying to import the variable from the original program(program.py) but it loops all code in program.py before moving on to newProgram.py. Any help would be appreciated (This only happens when the variable being imported comes from an input)
An example of this problem is:
# in program.py
question = input("Your greeting: ")
print("Hello")
import newProgram
# in newProgram.py
from program import question
if question == "Hi":
print("Why does it loop original file")
# This outputs:
Your greeting: Hi
Hello
Your greeting: Hi
Hello
Why does it loop original file
the code runs twice because of the third line in program.py:
import newProgram
This import runs the newProgram.py script again (which runs the program.py script).
So, if you're not using it, just get rid of this line and the code will work as expected.
So, I have been looking at other threads on this topic but they do not use the Module version of passing the argument to the other file, if so wasn't explained clearly enough for me to understand.
I have tried just to show I'm not just asking:
#MoneyCounter.py
import Password
enter = False
Password.system(enter)
def start(check):
if check == True:
main()
elif check == False:
print("Critical Error occured")
exit()
And my other file
#Password.py
import MoneyCounter
def system(check):
if check == False:
password() #This goes to password def not mentioned in this code
elif check == True:
MoneyCounter.start(check)
The error I am getting is the Module Password has no attribute system
The error I am getting is the Module Password has no attribute system
Of course it doesn't. The definition doesn't exist by the time the line of code is executed, since execution of the first file got interrupted by the import.
Either refactor or reorder your code so that the name isn't accessed until it exists, or remove the requirement that each module has for the other.
Your problem here is circular dependency/imports.
An import statement really executes the code in the imported file; that is, all the statements are executed, everything that is defed in the imported file gets defined etc. imports get imported, too.
So what's happening is this:
you run
$ python MoneyCounter.py
Python reads MoneyCounter.py, executes its first statement: import Password
Python reads Password.py, and executes its first statement: import MoneyCounter.py
Python reads MoneyCounter.py, this time it encounters import Password, but already has password in its list of known names; so it continues to
enter=False; Password.system(enter).
Now, Python already has a Password in its name lookup dictionary: the half-imported Password. In that, def system… hasn't happened yet, so Password.system is still unknown.
Generally, your architecture is questionable. Why would the Password "utility" module call into your "master" business logic? Better not do that, but write code that actually checks the return value of Password.system and acts based on that in your MoneyCounter.py.
On the assumption that MoneyCounter.py is the entry point (the name you run from the command-line), then I suggest you replace this:
enter = False
Password.system(enter)
with this:
if __name__ == "__main__":
enter = False
Password.system(enter)
That will only be executed from the entry-point (which is called __main__) and not when it is imported. However, you should reconsider your design.
Edit:
name is a reference to the text name of the current module. With modules that are explicitly imported the name is taken from the filename, but the entry-point (where the program starts) is always called __main__. So we can always test if we are running as an imported module or as an entry-point.
This test is extremely common in python. This way we can provide additional functionality depending on whether we run a module as a program or import it.
I have a Python script which is returning data by printing them, a function is not used.
I now want to make a function out of the script which works in the same way, but instead of printing the data, it should be returned by the app function.
Of course I could do it manually by writing "def myapp():", making all the indentations, and call it in the last line of the script, but I wonder if there is a tool for that?
Always write your script as one or more functions ending in two "magic" lines. A suitable template is
import sys # if you want a system return code
MY_CONSTANT = "whatever" # a symbolic constant
def a_function( args): # replace with your useful stuff
pass
# def b_function( args): # as many more defs as are useful
# can refer to / use both a_function (above) and c_function (below)
# def c_function()
# etc
def main():
print( "Script starting ...")
# parse arguments, if any parsing needed
# do stuff using the functions defined above
# print output, if needed
print( "End of script")
sys.exit(0) # 0 is Linux success, or other value for $? on exit
# "magic" that executes script_main only if invoked as a script
if __name__ == "__main__": # are we being invoked directly from command line?
main() # if so, run this file as a script.
Why? This file (myfile.py) is also usable as an import, at the interpreter prompt or in another file / script / module. It will define the constants and functions but it will not actually run anything when being imported as below. Either
import myfile
so you can refer to myfile.a_function, myfile.MY_CONSTANT, etc.
Or
from myfile import a_function
and then you can invoke a_function(args) without needing the prefix. You'll often see test or some random name: main() is not special.
This question already has answers here:
Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)?
(5 answers)
Closed 5 months ago.
Consider:
#! /usr/bin/python
def main():
print("boo")
This code does nothing when I try to run it in Python 3.3. No error or anything.
What’s wrong?
gvim script
chmod 775 script
./script
You still have to call the function.
def main(): # declaring a function just declares it - the code doesn't run
print("boo")
main() # here we call the function
I assumed you wanted to call the print function when the script was executed from the command line.
In Python you can figure out if the script containing a piece of code is the same as the script which was launched initially by checking the __name__ variable against __main__.
#! /usr/bin/python
if __name__ == '__main__':
print("boo")
With just these lines of code:
def main():
print("boo")
you're defining a function and not actually invoking it. To invoke the function main(), you need to call it like this:
main()
You need to call that function. Update the script to:
#! /usr/bin/python
def main():
print("boo")
# Call it
main()
In Python, if you want to write a script to perform a series of small tasks sequentially, then there is absolutely no need to write a function to contain them.
Just put each on a line on its own; or use an expression delimiter like ; (not really recommended, but you can do is you so desire), likewise:
task1
task2
task3
task4
or
task1; task2; task3; (again **not** really recommended, and certainly not pythonic)
In your case your code could be turned to something like:
print('boo')
print('boo2')
print('boo3')
and it would still act as you expect it to, without the main() method, as they get evaluated sequentially.
Please note that the reason you might want to create a function for these series of tasks is:
to present a nice interface (to clients of the code),
or to encapsulate repeated logic
There might be more uses, but that's the first I can come up with, and serve to prove my point.
Now, if you feel compelled to write code that resembles the main() method in other programming languages, then please use the following Python idiom (as stated by other users so far):
if __name__ == '__main__':
doSomething()
The above is working as follows:
When you import a Python module, it gets a string (usually, the name under which it was imported) assigned as its __name__ attribute.
When you execute a script directly (by invoking the Python vm and passing it the script's name as an argument), the __name__ attribute is set to __main__
So when you use the above idiom, you can both use the script as a pluggable module by importing it at will, or just execute it directly to have the series of expressions under the if __name__ == '__main__': be evaluated directly.
Should you feel the need to dig through more information, my sources were the following:
Python documentation: Modules
Python documentation: Executing modules as scripts
Python documentation: The data model (search for __name__)
If you find the other answers confusing or intimidating, here's a parable which should hopefully help. Look at the following Python program:
a = 34
When it runs, it does something: before exiting the script, Python learns that there is a variable a and that its value is the integer 34. It doesn't do anything with this information, but it's a complete program which does something. In order for it to produce some actual value, it needs to interact with its environment, though. What does it do with this value? It could create 34 directories, or ping the 34th server in your data center, or check the strength of the passwords of the newest 34 users in your database, or whatever; or just print something.
a = 34
print(a)
The following program is in some sense very similar to the first one.
def b():
a = 34
print(a)
When you run this program, it does something: Python now knows that there is a function named b, and that it doesn't take any arguments, and that it contains some syntactically valid Python code which will be run when some other code calls it, but it doesn't actually do anything with this code yet. In order to observe any value being produced by the code in the function, you have to actually call it:
b()
(As an aside, maybe also note that the local variable a inside the function declaration b is distinct from the global variable with the same name.)
I want to input code in Python like \input{Sources/file.tex}. How can I do it in Python?
[added]
Suppose I want to input data to: print("My data is here"+<input data here>).
Data
1, 3, 5, 5, 6
The built-in execfile function does what you ask, for example:
filename = "Sources/file.py"
execfile( filename )
This will execute the code from Sources/file.py almost as if that code were embedded in the current file, and is thus very similar to #include in C or \input in LaTeX.
Note that execfile also permits two optional arguments allowing you to specify the globals and locals dicts that the code should be executed with respect to, but in most cases this is not necessary. See pydoc execfile for details.
There are occasional legitimate reasons to want to use execfile. However, for the purpose of structuring large Python programs, it is conventional to separate your code into modules placed somewhere in the PYTHONPATH and to load them using the import statement rather than executing them with execfile. The advantages of import over execfile include:
Imported functions get qualified with the name of the module, e.g. module.myfunction instead of just myfunction.
Your code doesn't need to hard-code where in the filesystem the file is located.
You can't do that in Python. You can import objects from other modules.
otherfile.py:
def print_hello():
print "Hello World!"
main.py
import otherfile
otherfile.print_hello() # prints Hello World!
See the python tutorial
Say you have code in "my_file.py". Any line which is not in a method WILL get executed when you do:
import my_file
So for example if my_file.py has the following code in it:
print "hello"
Then in the interpreter you type:
import my_file
You will see "hello".
My question was clearly too broad, as the variety of replies hint -- none of them fully attack the question. The jchl targets the scenario where you get python-code to be executed. The THC4k addresses the situation where you want to use outside objects from modules. muckabout's reply is bad practice, as Xavier Ho mentioned, why on earth it uses import when it could use exec as well, the principle of least privileges to the dogs. One thing is still missing, probably because of the conflict between the term python-code in the title and the addition of data containing integers -- it is hard to claim that data is python-code but the code explains how to input data, evaluations and executable code.
#!/usr/bin/python
#
# Description: it works like the input -thing in Tex,
# you can fetch outside executable code, data or anything you like.
# Sorry I don't know precisely how input(things) works, maybe misusing terms
# or exaggerating.
#
# The reason why I wanted input -style thing is because I wanted to use more
# Python to write my lab-reports. Now, I don't need to mess data with
# executions and evalutions and data can be in clean files.
#TRIAL 1: Execution and Evaluation not from a file
executeMe="print('hello'); a = 'If you see me, it works'";
exec( executeMe )
print(a);
#TRIAL 2: printing file content
#
# and now with files
#
# $ cat IwillPrint007fromFile
# 007
f = open('./IwillPrint007fromFile', 'r');
msg = f.read()
print("If 007 == " + msg + " it works!");
# TRIAL 3: Evaluation from a file
#
# $cat IwillEvaluateSthing.py
# #!/usr/bin/python
# #
# # Description:
#
#
# evaluateMe = "If you see me again, you are breaking the rules of Sky."
f = open('./IwillEvaluateSthing.py', 'r');
exec(f.read());
print(evaluateMe);