I just started coding in python3 and for a school project we had to write a .txt file with the matrix in it and a .py file in which i am supposed to import the .txt file and execute the code. Everything should be executed in cmd with the following syntax: python matrix_input.txt matrixReloaded.py.
But i execute the code in cmd i get the following error: can't find 'main' module.
The .txt file i a simple text file with just the matrix in it.
In my .py file I had to create a directory for both the .txt file and the .py file and then follows the code that executes certain stuff on the matrix.
I tried multiple stuff but since I'm new to this nothing worked.
How do i fix this?
In order for a python script to execute it needs to have an entry point defined. That entry point is the main module. You are getting the error because it's not defined in your script. So, in your script, matrixReloaded.py, you want to include this module like this:
if __name__ == "__main__":
do_something()
Now, in order to execute the script from shell, you need to specify the script, and only then the arguments that you are trying to pass (in your case, a name of a file): python matrixReloaded.py matrix_input.txt
Lastly, to access the arguments (and then open the file or whatever you need to do with it), you will need to include the sys module. Here's an example:
import sys
if __name__ == "__main__":
print sys.argv[0] # prints matrixReloaded.py
print sys.argv[1] # prints matrix_input.txt
Related
I have couple questions regarding running code from multiple files from one .py file
When I import the Files with
from [subfolder] import [First scriptname - without .py]
from [subfolder] import [Second scriptname - without .py]
the scripts start running instantly, like if my scripts have a print code it would look like this after running the combined-scripts file
print("Hi Im Script One")
print("Hi Im Script Two")
now I could put them in functions and run the functions but my files also have some variables that are not inside functions, the question I have is if there is a way to not start the script automatically after import?
Also what happens with variables inside these scripts, are they usable throughout the combined file or do i need to state them with something like "global"?
is there a way to not start the script automaticly after import?
This is what python's if __name__ == "__main__": is for.
Anything outside that (imports, etc.) will be run when the .py file is imported.
what happens with variables inside these scripts, are they usable troughout the combined file or do i need to state them with something like "global"?
They may be best put inside a class, or you can also (not sure how Pythonic/not this is):
from [FirstScriptName_without_.py] import [className_a], [functionName_b], [varName_c]
This question already has answers here:
How to reliably open a file in the same directory as the currently running script
(9 answers)
Closed 1 year ago.
I'm looking for a way to open another python file in the same folder, but it could be anywhere on a PC. (i.e when I send it to someone the program should be able to find it's way to the file (blahblahblah\IDLE\Login,py).
Here is the code I currently have after some googling, but I really have no idea what I'm doing.
from subprocess import call
import subprocess
import os
def main():
subprocess.call(['bash' , os.path.expanduser('~') + "\IDLE\Login.py" ] )
if __name__ == '__main__':
main()
I know that one of the subprocess imports are redundant but it's just a remnant of older code while I try to find this new way.
The end goal of the project is to use the main file and turn it into an executable to run all the other files in the directory which are called by each other.
Many thanks!
This will give you a full path to the script's location
print('sys.argv[0] =', sys.argv[0])
pathname = os.path.dirname(sys.argv[0])
print('path =', pathname)
print('full path =', os.path.abspath(pathname))
Here's how to run bash to execute a script named "Login.py" that is in the same directory as the currently running Python file:
import subprocess
import os
def main():
here = os.path.dirname(os.path.abspath(__file__))
subprocess.call(['bash', os.path.join(here, "Login.py")])
if __name__ == '__main__':
main()
__file__ is always the path of the file containing the Python code being executed.
I don't know why you want to run bash on a .py file, but the mechanics would be the same if you wanted to run python instead or wanted to run bash on a file named Login.sh.
Hi I am pretty new to python so I have been playing around with it. I recently created 2 files for some process I am working on which seems to be working while running python but doing nothing when write python name.py argv at the unix command line. It is probably something basic and I would appreciate some help.
1st file (make_dir.py)
import os
import sys
def main():
directory = sys.argv[1]
if not os.path.exists(directory):
os.makedirs(directory)
at unix terminal I write
python make_dir.py /home/user/Python/Test/
result: Test folder is not created.
the second file has probably the same issue.
2nd file directory.py
import sys
import os
def main():
os.chdir(sys.argv[1])
File = open(sys.argv[2] , 'w')
File.write(sys.argv[3])
File.close()
at unix terminal:
python directory.py /home/user/Python/TEST/ a.log "this is a test"
a.log is not created.
If I got some error messages I probably could figure it out but no messages. Any help is much appreciated.
You're defining a function called main, but never call it. Do:
import os
import sys
def main():
...
if __name__ == '__main__':
main()
See here for more details about this idiom.
You are not actually calling main. Simply adding main() at the end of script would suffice, but usually this idiom is used:
if __name__ == '__main__':
main()
This would call main if the script was executed directly, and not just imported from another module.
See executing modules as scripts
Python is not C and def main is not magic. There is no predefined execution entry point for Python programs. All your code is doing is defining a main function (not running it), so Python defines main and then stops (as you requested).
You must call main() explicitly if you want it to execute. You should use this idiom:
if __name__ == '__main__':
main()
__name__ is a magic variable created at the module level that contains the module's name. If __name__ is '__main__', it means the current module was not imported but was run directly. This idiom allows you to use a Python file as both a module (something you can import--where main() should not automatically run) and as a script (where main() should run automatically).
I often have to write data parsing scripts, and I'd like to be able to run them in two different ways: as a module and as a standalone script. So, for example:
def parseData(filename):
# data parsing code here
return data
def HypotheticalCommandLineOnlyHappyMagicFunction():
print json.dumps(parseData(sys.argv[1]), indent=4)
the idea here being that in another python script I can call import dataparser and have access to dataParser.parseData in my script, or on the command line I can just run python dataparser.py and it would run my HypotheticalCommandLineOnlyHappyMagicFunction and shunt the data as json to stdout. Is there a way to do this in python?
The standard way to do this is to guard the code that should be only run when the script is called stand-alone by
if __name__ == "__main__":
# Your main script code
The code after this if won't be run if the module is imported.
The __name__ special variable contains the name of the current module as a string. If your file is called glonk.py, then __name__ will be "glonk" if the the file is imported as a module and it will be "__main__" if the file is run as a stand-alone script.
While importing a python script from another script I want the script code that is classically protected by
if __name__ == "__main__":
....
....
to be run, how can I get that code run?
What I am trying to do is from a python script, dynamically change a module then import an existing script which should see the changes made and run its __main__ code like it was directly invoked by python?
I need to execute the 2nd python script in the same namespace as the 1st python script and pass the 2nd script command line parameters. execfile() suggested below might work but that doesn't take any command line parameters.
I would rather not edit the 2nd script (external code) as I want the 1st script to be a wrapper around it.
If you can edit the file being imported, one option is to follow the basic principle of putting important code inside of functions.
# Your script.
import foo
foo.main()
# The file being imported.
def main():
print "running foo.main()"
if __name__ == "__main__":
main()
If you can't edit the code being imported, execfile does provide a mechanism for passing arguments to the imported code, but this approach would make me nervous. Use with caution.
# Your script.
import sys
import foo
bar = 999
sys.argv = ['blah', 'fubb']
execfile( 'foo.py', globals() )
# The file being exec'd.
if __name__ == "__main__":
print bar
print sys.argv