I am creating python files through the course of running a python program. I then want to import these files and run functions that were defined within them. The files I am creating are not stored within my path variables and I'd prefer to keep it that way.
Originally I was calling the execFile(<script_path>) function and then calling the function defined by executing the file. This has a side effect of always entering the if __name__ == "__main__" condition, which with my current setup I can't have happen.
I can't change the generated files, because I've already created 100's of them and don't want to have to revise them all. I can only change the file that calls the generated files.
Basically what I have now...
#<c:\File.py>
def func(word):
print word
if __name__ == "__main__":
print "must only be called from command line"
#results in an error when called from CallingFunction.py
input = sys.argv[1]
#<CallingFunction.py>
#results in Main Condition being called
execFile("c:\\File.py")
func("hello world")
Use
m = __import__("File")
This is essentially the same as doing
import File
m = File
If I understand correctly your remarks to man that the file isn't in sys.path and you'd rather keep it that way, this would still work:
import imp
fileobj, pathname, description = imp.find_module('thefile', 'c:/')
moduleobj = imp.load_module('thefile', fileobj, pathname, description)
fileobj.close()
(Of course, given 'c:/thefile.py', you can extract the parts 'c:/' and 'thefile.py' with os.path.spliy, and from 'thefile.py' get 'thefile' with os.path.splitext.)
Related
I am trying to find a way to create a Windows shortcut that executes a function from a Python file.
The function being run would look something like this (it runs a command in the shell):
def function(command):
subprocess.run(command, shell = True, check = True)
I am aware that you can run cmd functions and commands directly with a shortcut, but I would like it to be controlled by Python.
I have little experience working with Windows shorcuts, so the best I can do is show you the following:
This is what I imagine it would like like.
After a quick Google search, the only help I can find is how to make a shortcut with Python, not how to run a function from it. So hopefully what I am asking is even possible?
Generally speaking AFAIK, you can't do it, however it could be done if the target script is written a certain way and is passed the name of the function to run as an argument. You could even add arguments to be passed to the function by listing them following its name in the shortcut.
The target script has to be set up with an if __name__ == '__main__': section similar to what is shown below which executes the named function it is passed as a command line argument. The input() call at the end is there just to make the console window stay open so what is printed can be seen.
target_script.py:
def func1():
print('func1() running')
def func2():
print('func2() running')
if __name__ == '__main__':
from pathlib import Path
import sys
print('In module', Path(__file__).name)
funcname = sys.argv[1]
vars()[funcname]() # Call named function.
input('\npress Enter key to continue...')
To make use of it you would need to create a shortcut with a Target: set to something like:
python D:\path_to_directory\target_script.py func1
Output:
In module target_script.py
func1() running
press Enter key to continue...
Generalizing
It would also be possible to write a script that could be applied to other scripts that weren't written like target_script.
run_func_in_module.py:
import importlib.util
from pathlib import Path
import sys
mod_filepath = Path(sys.argv[1])
funcname = sys.argv[2]
# Import the module.
spec = importlib.util.spec_from_file_location(mod_filepath.stem, mod_filepath)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Call the specified function in the module.
mod_func = getattr(module, funcname)
mod_func()
To make use of this version you would need to create a shortcut with a Target: set to something like:
python D:\path_to_directory\run_func_in_module.py D:\another_directory\target_script.py func2
Note that the target_script.py would no longer need the if __name__ == '__main__': section at the end (although having one would do no harm).
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
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.
I have been trying to debug the below python cgi code but doesn't seems to work. When i try in new file it these three lines seems to work
filename=unique_file('C:/wamp/www/project/input.fasta')
prefix, suffix = os.path.splitext(filename)
fd, filename = tempfile.mkstemp(suffix, prefix+"_", dirname)
But, when i try like this way then i get error unique_file is not define >>>
form=cgi.FieldStorage()
i=(form["dfile"].value)
j=(form["sequence"].value)
if (i!="" and j=="" ):
filename=(form["dfile"].filename)
(name, ext) = os.path.splitext(filename)
alignfile=name + '.aln'
elif(j!="" and i==""):
filename=unique_file('C:/wamp/www/project/input.fasta')
prefix, suffix = os.path.splitext(filename)
fd, filename = tempfile.mkstemp(suffix, prefix+"_", dirname)
file = open(filename, 'w')
value=str(j)
file.write(value)
file.close()
(name, ext) = os.path.splitext(filename)
alignfile=name + '.aln'
What i am trying to do is check two options from form:- Fileupload and textarea. If fileupload is true then there is nothing to do except separating file and its extension. But when textarea is true then i have to generate unique file name and write content in it and pass filename and its extension.
Error i got is...
type 'exceptions.NameError'>: name 'unique_file' is not defined
args = ("name 'unique_file' is not defined",)
message = "name 'unique_file' is not defined"
Any suggestions and corrections are appreciated
Thanks for your concern
unique_file() isn't a built-in function of Python. So I assume, either you forget a line in your first code snippet which actually imports this function, or you configured your python interpreter to load a startup file (http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP). In the second case, the CGI script can't find this function because it runs with the web server identity which probably lacks the PYTHONSTARTUP env. variable definition.
You need to either import or define your unique_file method before using it.
They will look something like:
from mymodule import unique_file
or:
def unique_file():
# return a unique file
Usually when a compiler or interpreter says something isn't defined, that's precisely what the problem is. So, you have to answer the question "why is it not defined?". Have you actually defined a method named "unique_file"? If so, maybe the name is misspelled, or maybe it's not defined before this code is executed.
If the function is in another file or module, have you imported that module to gain access to the function?
When you say it works in one way but not the other, what's the difference? Does one method auto-import some functions that the other does not?
Since unique_file is not a built-in command, you're probably forgetting to actually define a function with that name, or forgetting to import it from an existing module.
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);