I made this small program :
I wanna know how to automatically call it, so that when I open the .py it shows up immediatly.
Please understand that I am a beginner in Python.
The right way to do this is to add the following statement in the end of the file:
if __name__ == "__main__":
table_par_7()
Explanation
This will ensure that if you open the file directly (and thus makes it the main file), the function will run, but if another python file imports this file (thus this file isn't the main one), it wont run.
You can call it like this:
# Add this lines at the end of your code
table_par_7()
If you mean:- (1) When you will run the .py file, how to call it. Then the answer is, you will have to write the name of function and press ENTER to execute it.
(2) When you will open the .py file from any folder, is it possible to print final result. The the answer is a big NO. This is because using def in any program is just a keyword to create function. It do not have any property by which it will execute by its own. It must be called by the system which is known as system call.
Related
I am a Python beginner and wrote some Python code that I want to run from my C# code.
In all the answers I have seen already, the way was to make a .exe file from the .py one and run it by system call.
However, I want it so that I do not need to make the .exe file and can write the commands with arguments as I could in the command line.
C:\Users\ntuser> python C:\Users\ntuser\Documents\run_python.py 3
Is there a way to do it?
I found a way to pass just one command—but I need to make two: 1. Go to "C:\Users\ntuser" 2. Run the Python code.
Thanks!
OK, so I found a solution.
Thanks to UnholySheep for the help.
What you need to do is:
Make the python as system variable
Go by code to your home directory:
Directory.SetCurrentDirectory(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
Add this code for calling the python code:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;//if you want to hide the window
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C python pytonPath\\python_code.py";
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();//if you want to wait
I am writing a Python script with the following objectives:
Starting from current working directory, change directory to child directory 'A'
Make slight adjustments to a fort.4 file
Run a Fortran binary file (the syntax of which is ../../../../ continuing until I hit the folder containing the binary); return to 2. until my particular objective is complete, then
Back out of child directory to parent, then enter another child directory and return to 2. until I have iterated through all the folders in question.
The code is coming along well. I am having to rely heavily upon Python's OS module for the directory work. However, I have never had any experience a) making minor adjustments of a file using python and b) running an executable. Could you guys give me some ideas on Python modules, direct me to a similar stack source etc, or perhaps give ways that this can be accomplished? I understand this is a vague question, so please ask if you do not understand what I am asking and I will elaborate. Also, the changes I have to make to this fort.4 file are repetitive in nature; they all happen at the same position in the file.
Cheers
EDIT::
entire fort.4 file:
file_name
movie1.dat !name of a general file the binary reads
nbr_box ! line3-8 is general info
2
this_box
1
lrdf_bead
.true.
beadid1
C1 !this is the line I must change
beadid2
F4 !This is a second line I must change
lrdf_com
.false.
bin_width
0.04
rcut
7
So really, I need to change "C1" to "C2" for example. The changes are very insignificant to make, but I must emphasize the fact that the main fortran executable reads this fort.4, as well as this movie1.dat file that I have already created. Hope this helps
Ok so there is a few important things here, first we need to be able to manage our cwd, for that we will use the os module
import os
whenever a method operates on a folder it is important to change directories into the folder and back to the parent folder. This can also be achieved with the os module.
def operateOnFolder(folder):
os.chdir(folder)
...
os.chdir("..")
Now we need to do some method for each directory, that comes with this,
for k in os.listdir(".") if os.path.isdir(k):
operateOnFolder(k)
Finally in order to operate on some preexisting FORTRAN file we can use the builtin file operators.
fileSource = open("someFile.f","r")
fileText = fileSource.read()
fileSource.close()
fileLines = fileText.split("\n")
# change a line in the file with -> fileLines[42] = "the 42nd line"
fileText = "\n".join(fileLines)
fileOutput = open("someFile.f","w")
fileOutput.write(fileText)
You can create and run your executable output.fx from source.f90::
subprocess.call(["gfortran","-o","output.fx","source.f90"])#create
subprocess.call(["output.fx"]) #execute
The following code is written in the morph.py file:
with open("morph.py", "r+") as f:
old = f.read() # read everything in the file
f.seek(0,2) # rewind
f.write("1") # write the new line before
a="BAD"
a1="Worked"
print a
The idea is that the morph.py file will be rewritten, and the text "Worked" will be printed.
This is not the case, I think it has to do with how Python interpreter loads the files. The only thing that makes sense is that the whole file is loaded, and then run.
Can somebody shed some light? Is it even possible to have self morphing code in python?
Partially related question:
Self decompressing and executing code in python
Not in the way you're trying to do it.
Before Python starts executing any piece of code, it compiles it into a bytecode representation, which is much faster to execute than reading line-by-line. This means that after Python has compiled the file, no changes to the file will be reflected in currently-running code.
However, you can manually load code from strings by using compile, exec, or eval. You can use this to create a program that is passed its own source code, alters and returns it, and executes the modified source code.
When I run the file the first time it outputs:
BAD
When I run it a second time it outputs:
Worked
Any subsequent times it will give an error:
... name 'a11' is not defined
When you run python on a file, it will load the file, then convert it to bytecode, then execute the bytecode. The file has already undergone conversion when you change the file, so you see no effect.
Please excuse what I know is an incredibly basic question that I have nevertheless been unable to resolve on my own.
I'm trying to switch over my data analysis from Matlab to Python, and I'm struggling with something very basic: in Matlab, I write a function in the editor, and to use that function I simply call it from the command line, or within other functions. The function that I compose in the matlab editor is given a name at the function definition line, and it's generally best for the function name to match the .m file name to avoid confusion.
I don't understand how functions differ in Python, because I have not been successful translating the same approach there.
For instance, if I write a function in the Python editor (I'm using Python 2.7 and Spyder), simply saving the .py file and calling it by its name from the Python terminal does not work. I get a "function not defined" error. However, if I execute the function within Spyder's editor (using the "run file" button), not only does the code execute properly, from that point on the function is also call-able directly from the terminal.
So...what am I doing wrong? I fully appreciate that using Python isn't going to be identical to Matlab in every way, but it seems that what I'm trying to do isn't unreasonable. I simply want to be able to write functions and call them from the python command line, without having to run each and every one through the editor first. I'm sure my mistake here must be very simple, yet doing quite a lot of reading online hasn't led me to an answer.
Thanks for any information!
If you want to use functions defined in a particular file in Python you need to "import" that file first. This is similar to running the code in that file. Matlab doesn't require you to do this because it searches for files with a matching name and automagically reads in the code for you.
For example,
myFunction.py is a file containing
def myAdd(a, b):
return a + b
In order to access this function from the Python command line or another file I would type
from myFunction import myAdd
And then during this session I can type
myAdd(1, 2)
There are a couple of ways of using import, see here.
You need to a check for __main__ to your python script
def myFunction():
pass
if __name__ == "__main__":
myFunction()
then you can run your script from terminal like this
python myscript.py
Also if your function is in another file you need to import it
from myFunctions import myFunction
myFunction()
Python doesn't have MATLAB's "one function per file" limitation. You can have as many functions as you want in a given file, and all of them can be accessed from the command line or from other functions.
Python also doesn't follow MATLAB's practice of always automatically making every function it can find usable all the time, which tends to lead to function name collisions (two functions with the same name).
Instead, Python uses the concept of a "module". A module is just a file (your .py file). That file can have zero or more functions, zero or more variables, and zero or more classes. When you want to use something from that file, you just import it.
So say you have a file 'mystuff.py':
X = 1
Y = 2
def myfunc1(a, b):
do_something
def myfunc2(c, d):
do_something
And you want to use it, you can just type import mystuff. You can then access any of the variables or functions in mystuff. To call myfunc2, you can just do mystuff.myfunc2(z, w).
What basically happens is that when you type import mystuff, it just executes the code in the file, and makes all the variables that result available from mystuff.<varname>, where <varname> is the name of the variable. Unlike in MATLAB, Python functions are treated like any other variable, so they can be accessed just like any other variable. The same is true with classes.
There are other ways to import, too, such as from mystuff import myfunc.
You run python programs by running them with
python program.py
I was wondering if someone could give me a direction on how to give functions to a file... This is a bit hard to explain, so I'll try my best.
Let's say I have an application (using wxPython) and let's say that I have a file. Now this file is assigned to open with the application. So, I double-click the file and it opens the application. Now my question is, what would have to be written on the file to, for example, open up a dialog? So we double-click the file and it opens a dialog on the application?
PS: I know that I have first to associate the program with a certain file type to double-click it, but thats not the question.
AFAIK most platforms just call the helper app with the file you clicked on as an argument, so your filepath will be in sys.argv[1]
I think what he wants to do is associate a file extension to his application so when he opens the file by double clicking it, it sends the contents of the file to his app; in this case, display the contents within a Dialog?
If this is the case, than the first thing you would need to do (provided you are on windows) is create the appropriate file association for your file extention. This can be done through the registry and when setup correctly will open your app with the the path/filename of the file that was executed as the first argument. Ideally it is the same as executing it from the command line like:
C:\your\application.exe "C:\The\Path\To\my.file"
Now as suggested above, you would then need to use sys.argv to to obtain the arguments passed to your application, in this case C:\Path\To\my.file would be the first argument. Simply put, sys.argv is a list of arguments passed to the application; in this case the first entry sys.argv[0] will always be the path to your application, and as mentioned above, sys.argv[1] would be the path to your custom file.
Example:
import sys
myFile = sys.argv[1]
f = file(myFile, "r")
contents = f.read()
f.close()
Then you will be able to pass the variable contents to your dialog to do whatever with.