def main():
names = []
for line in ins:
number_strings = line.split() # Split the line on runs of whitespace
data.append(numbers_strings) # Add the "row" to your list.
print(data)
I tried using this code to print a text file that looks like this
name num1 num2 C/N
I am trying to print this but when I run the command "python3 file.py" no output occurs. instead of printing the contents of the file I am putting in
Unlike in C, execution in python does not begin from the main method, as python follows a top-down approach. What you'll need to do is explicitly invoke the main method to have it run.
def main():
...
main()
If you want the main method to run only when invoked through the script (and not when imported), specify under what __name__ it should run:
def main():
...
if __name__ == '__main__':
main()
For more information, read
What does if __name__ == "__main__": do?
Understanding the main method of python
If you just want to execute that code you can forget about the main function and just write your code
names = []
for line in ins:
number_strings = line.split() # Split the line on runs of whitespace
data.append(numbers_strings) # Add the "row" to your list.
print(data)
If you do want to use a main function follow the community wiki answer.
Related
I want to execute a Python file from another Python file and show all print() outputs and error outputs without waiting (realtime).
The simplified version of my code is as follows and I would like to show "start" and an error message without waiting for "end" (the end of the script).
def main():
# Function that takes a long time (in my actual code)
x += 1 # this raises an error
if __name__ == "main":
print("start")
main()
print("end")
I also have run.py:
import subprocess
def run():
subprocess.run(["python", "main.py"])
if __name__ == '__main__':
run()
I tried this blog post and several other similar answers on stackoverflow, but none of them worked, so I decided to put my original code here, which is above.
The following seems to work for me (on Windows). It uses subprocess.Popen() to execute the other script because this gives more control over what goes on. It turns buffering off to eliminate any delays that might cause, plus it redirects stderr to stdout to so all output can be retrieved from a single source.. Also note it also includes the correction #Ketan Mukadam mentions is his answer tregarding the value of __name__ in your first script.
main_script.py:
def main():
# Function that takes a long time (in my actual code)
x += 1 # this raises an error
if __name__ == '__main__':
print("start")
main()
print("end")
run.py:
import subprocess
import sys
def run():
kwargs = dict(bufsize=0, # No buffering.
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, # Redirect stderr to stdout.
universal_newlines=True)
args = [sys.executable, 'main_script.py']
with subprocess.Popen(args, **kwargs).stdout as output:
for line in output:
print(line, end='') # Process the output...
if __name__ == '__main__':
run()
Output from executing run.py:
start
Traceback (most recent call last):
File "main_script.py", line 10, in <module>
main()
File "main_script.py", line 6, in main
x += 1 # this raises an error
UnboundLocalError: local variable 'x' referenced before assignment
Is this line a mistake?
if __name__ == "main":
The symbol is __main__ set by interpreter and not main. It is possible that because of this typo error no code is running from main script. Try first executing the main script directly on command shell.
I have a python file B with all my function and a main code which is in loop of 0.25 sec, and I want to call this file in a loop in my file A. Can you get my weird mind ?
What I did but only read the loop from file B once :
#FileA
while 1:
from FileB import *
And my file B :
#FileB
while t<0.25:
#my stuff
Thanks.
PS : I forget to mention that i can't modify the file B.
The import statement only reads the target module one time.
If you have control of both files, I'd suggest that you make your loop a function in file B:
def main():
while t<0.25:
#my stuff
if __name__ == '__main__':
main()
Then you can call it repeatedly from file A:
from fileB import main as Bmain
while 1:
Bmain()
If you don't have control of the source code for the files (meaning: if the code comes from someone else), there are a few options. Probably the easiest and fastest to code would be to use the os.system(command) function to run the contents of fileB in a separate process.
You should use functions, you don't have any functions in your questions. Here is an example:
# fileA.py
import time
from fileB import myFunction
def main():
while True:
ret = myFunciton()
time.sleep(3)
main()
# fileB.py
def myFunction():
print "running myFunction"
return "result"
This is what I have right now:
def open_file():
file_name = input("What is the name of the file you want to open?")
while True:
try:
file = open(file_name, 'r')
header = file.readline()
return (file)
break
except FileNotFoundError:
file_name = input("What is the name of the file you want to open?")
def process_file():
file = open_file()
print(file)
def main():
process_file()
I can't even get it to get to prompting me for the file name I want to open. Doesn't that mean it's not a problem with my loop but the way I am calling my functions?
Assuming you called your module something like foo.py
You could add this bit of code:
if __name__ == '__main__':
main()
And then in the console run:
>>python foo.py
For an explanation of why this works, you can see this answer: What does if __name__ == "__main__": do?
You need to call main() to run your code. If you do that it works just fine.
You need to call main() in order for your code to run.
Im using pycharm and it says Process finished with exit code 0 without my restaurant_list or anything after it
def main():
# Make a list of resturaunts the resturaunteur could go to
restaurants_list = ['Mcdonalds', 'BurgerKing', 'Wendys', 'PaneraBread']
print(restaurants_list)
# Remove expensive resturaunt from the list
print('Here are the restaurants in the list')
print(restaurants_list)
# Get the restaurant to change
restaurant = input('Which restaurant to remove?')
# Remove the restauraunt
restaurants_list.remove(restaurant)
#Display the list
print('Here is the revised list')
print(restaurants_list)
if __name__ == "__main__":
main()
You need to add the following at the end of the file:
if __name__ == "__main__":
main()
... to call your main function. Also make sure your PyCharm is configured to run the right script.
I have a file (test.py) that receives sys.argv from the console/bash:
import sys
def main():
ans = int(sys.argv[1])**int(sys.argv[1])
with open('test.out', 'w') as fout:
fout.write(str(ans))
if __name__ == '__main__':
main()
Usually, I could just do $ python test.py 2 to produce the test.out file. But I need to call the main() function from test.py from another script.
I could do as below in (call.py) but is there any other way to run pass an argument to sys.argv to main() in `test.py?
import os
number = 2
os.system('python test.py '+str(number))
Please note that I CANNOT modify test.py and I also have a main() in call.py which does other things.
You can use your program as it is. Because, irrespective of the file invoked by python, all the python files will get the command line arguments passed.
But you can make the main function accept sys.argv as the default parameter. So, main will always take the sys.argv by default. When you pass a different list, it will take the first element and process it.
test.py
import sys
def main(args = sys.argv):
ans = int(args[1])**int(args[1])
with open('test.out', 'w') as fout:
fout.write(str(ans))
call.py
import sys, test
test.main()
Write that like:
import sys
def main(num):
ans = int(num)**int(num)
with open('test.out', 'w') as fout:
fout.write(str(ans))
if __name__ == '__main__':
main(sys.argv[1])
so that your main() function doesn't have to know about sys.argv - it just handles the parameters being passed in to it.
Without modifying test.py you can still run it just as you have it, just do call.py:
import test
test.main()
then $ python call.py ARG will still work. Since you've already imported sys in test, you don't need to reimport it unless you want to use sys in call.py. Note that sys.argv[0]=='call.py' not test.py if use test through call.
Create a function to do your calculation and file writing, which can be called from any other module:
power.py:
import sys
def power(arg):
ans = arg ** arg
with open('test.out', 'w') as fout:
fout.write(str(ans))
if __name__ == '__main__':
power(int(sys.argv[1]))
other.py:
import power
power.power(2)