I am attempting to import several variables from one file into another file, without running the first file twice. Specifically, I have a script called "run_all_files.py" which loops through files in a local directory to be run in sequence, and this is the script through which I want to execute the files in question. In the file "file_1.py", I want to import the variables A and B into "file_2.py" but I do not want "file_1.py" to re-run.
I have also attempted to invoke if __name__=='__main__': function, but cannot get variables A and B to import by themselves, and "file_1.py" still runs twice. Both "file_1.py" and "file_2.py" are located in the path listed and are executed when running "run_all_files.py".
"run_all_files.py"
import os
path = "C:\\users\\mdl518\\Desktop\\"
def run_the_files():
file_list = ['file_1.py', 'file_2.py']
for filename in file_list:
os.system('python' + ' ' + os.path.join(path,filename))
run_the_files()
"file_1.py"
import os
def run_first_file():
global A, B
A = 'Hello'
B = 'User'
C = 'Python Programmer'
print("This is the first file to run")
run_first_file()
"file_2.py"
import os
from file_1 import A,B
def run_second_file():
print('Welcome, and ', A + ' ' + B)
print("This second program runs smoothly")
run_second_file()
Current output:
This is the first file to run
This is the first file to run
Welcome, and Hello User
This second program runs smoothly
Desired output:
This is the first file to run
Welcome, and Hello User
This second program runs smoothly
** Update: Change file_list in "run_all_files.py" to file_list = ['file_2.py'] to achieve the desired output **
One possibility would be if you go via a class, is definitely not elegant, but works.
"file_1.py"
from var import sol
class v(object):
sol = 'Hello'
"file_2.py"
from var import v
print(v.sol)
Related
I have a main.py file
import common_functions as conf
print("Main File:")
filename = conf.testing()
from TC import TC
and I want to assign the below return statement as a variable "filename"
common_functions.py
def testing():
print("This should only print once!")
return "awesome file"
I want to then be able to access this variable, in another file that I am importing (TC )
TC.py
from main import filename
print("TC File:")
print(f"Filename is: {filename}")
however, currently, if I do this, then the output is:
Main File:
This should only print once!
Main File:
This should only print once!
TC File:
Filename is: awesome file
I am really struggling with this one, as I am trying to pass a variable into the called scripts, but that variable is only named from another function... so it seems as though everytime I it's called, then the function kicks off again
I would like to be able to set the variable filename in the main file from the function it is calling, and then in the called file (TC.py) I would like to be able to access that variable as a string, not rerun everything.
Is that possible?
I am currently attempting to pass a variable from my C# winforms application to my Python executable through process.start(). The script uses shutil to duplicate and rename a separate python file, the file will be renamed with respect to a variable (var, c# variable)...
I want to pass the "current" text-box value of my winforms
application to my Python script and run into a name error on my
python script. In my script, after clicking a button ,through
openFileDialog, I select a excel sheet file in the FileDialog and the
full path to the file is pasted in a textbox, "Textboxpath." Here I
want to pass the textbox value (the Textboxpath value) of my winforms application to my Python script.
My issue is defining the C# variable current value or value to my Python script. My windows form application runs perfectly with the current script though when I attempt to run my Python script and pass the C# variable through ".Arguments", my Python file returns with "NameError: name 'Textboxpath' is not defined." I have attempted to rewrite the process.start() function including the variable in my python script there has been no success to defining the variable, any help would be very appreciated!
**C#:**
...
#script for defining openFileDialog variable and using OpenFileDialog goes here
Textboxpath.Text = openFileDialog.FileName; #prints file (excel workbook) directory path to text box
...
string var;
var = Textboxpath.Text;
ProcessStartInfo StartInfo
= new ProcessStartInfo(#"C:\directorytask\dist\modifyfest.exe");
StartInfo.FileName = "C:\\directorytask\\dist\\modifyfest.exe";
StartInfo.Arguments = var;
Process.Start(StartInfo);
**Python script: modifyfest.exe** #packaged with pyinstaller, --onefile
import os
import sys
import shutil
x = var
f = x - '.xlsx'
l = f - 'C:\directorytask'
k = '.py'
y = 'test_'
z = y + l +k
#duplicating/renaming python file
original = 'C:/directorytask/test_five.py' #original python file
target = 'C:/directorytask/' + z #original python file being duplicated with name z
shutil.copyfile(original, target)
**Error:**
Traceback <most recent call last>:
File "modifyfest.py", line 5, in <module>
NameError: name 'Textboxpath' is not defined
[34652] failed to execute script modifyfest
I added the parser! This is how the Python script looks now, runs perfect...
**answer:**
import os
import sys
import shutil
from pathlib import Path
def parse(p):
q = p
return q
x = parse(sys.argv[1]) #imports first argument sent by c#, I attempted sys.argv[0] instead and it returned the first line of my c# ProcessStartInfo list, file name...
p = Path(x).stem
k = '.py'
y = 'test_'
z = y + p +k
original = 'C:/directorytask/test_five.py' #retailer specific duplicated task
target = 'C:/directorytask/' + z #task being created
shutil.copyfile(original, target)
I have 2 files prgm.py and test.py
1.prgm.py
def move(self)
H=newtest.myfunction()
i= H.index(z)
user=newuser.my_function()
print(user[i])
How will i get user[i] in the other code named test.py
Use an import statement in the other file;
Like this - from prgm import move
Note: For this to work both of the files needs to be in the same folder or the path to the file you are importing needs to be in your PYTHONPATH
Instead of printing the result, you can simply return it. In the second file, you just import the function from this source file and call it.
Given the situation, move is actually a class method, so you need to import the whole class and instance it in the second file
prgm.py
class Example:
def move(self):
H = newtest.myfunction()
i = H.index(z)
user = newuser.my_function()
return user[i]
test.py
from prgm import Example
example = Example()
user = example.move()
# do things with user
It is the first time I write as I really didn't find any solution to my issue.
I want to allow my user to launch some Python program from Excel.
So i have this VBA code at some point:
lg_ErrorCode = wsh.Run(str_PythonPath & " " & str_PythonArg, 1, bl_StopVBwhilePython)
If lg_ErrorCode <> 0 Then
MsgBox "Couldn't run python script! " _
+ vbCrLf + CStr(lg_ErrorCode)
Run_Python = False
End If
str_PythonPath = "C:\Python34\python.exe C:\Users\XXXX\Documents\4_Python\Scan_FTP\test.py"
str_PythonArg = "arg1 arg2"
After multiple testing, the row in error in Python is when I try to import another module (I precise that this VBA code is working without the below row in Python):
import fct_Ftp as ftp
The architecture of the module is as follow:
4_Python
-folder: Scan_FTP
- file: test.py (The one launch from VBA)
-file: fct_Ftp.py
(For information, I change the architecture of the file, and try to copy the file at some other position just to test without success)
The import has no problem when I launch Test.py directly with:
import sys, os
sys.path.append('../')
But from VBA, this import is not working.
So I figured out this more generic solution, that dont work as well from Excel/VBA
import sys, os
def m_importingFunction():
str_absPath = os.path.abspath('')
str_absPathDad = os.path.dirname(str_absPath)
l_absPathSons = [os.path.abspath(x[0]) for x in os.walk('.')]
l_Dir = l_absPathSons + [str_absPathDad]
l_DirPy = [Dir for Dir in l_Dir if 'Python' in Dir]
for Dir in l_DirPy:
sys.path.append(Dir)
print(Dir)
m_importingFunction()
try:
import fct_Ftp as ftp
# ftp = __import__ ("fct_Ftp")
write += 'YAAAA' # write a file YAAAA from Python
except:
write += 'NOOOOOO' # write a file NOOOOO from VBA
f= open(write + ".txt","w+")
f.close()
Can you please help me as it is a very tricky questions ?
Many thanks to you guys.
You are able to start your program from the command line?
Why not create a batch file with excel which you then start in a shell?
I'm creating a really basic program that simulates a terminal with Python3.6, its name is Prosser(The origin is that "Prosser" sounds like "Processer" and Prosser is a command processer).
A problem that I'm having is with command import, this is, all the commands are stored in a folder called "lib" in the root folder of Prosser and inside it can have folders and files, if a folder is in the "lib" dir it can't be named as folder anymore, its name now is package(But this doesn't care for now).
The interface of the program is just a input writed:
Prosser:/home/pedro/documents/projects/prosser/-!
and the user can type a command before the text, like a normal terminal:
Prosser:/home/pedro/documents/projects/prosser/-! console.write Hello World
let's say that inside the "lib" folder exists one folder called "console" and inside it has a file called "write.py" that has the code:
class exec:
def main(args):
print(args)
As you can see the first 2 lines is like a important structure for command execution: The class "exec" is the main class for the command execution and the def "main" is the main and first function that the terminal will read and execute also pass the arguments that the user defined, after that the command will be responsible to catch any error and do what it will be created to do.
At this moment, everything is ok, but now comes the true help that I need of U guys, the command import.
Like I writed the user can type any command, and in the example above I typed a "console.write Hello World" and exists one folder called "console" and one file "write.py". The point is that the packages can be defined by a "dot", this is:
-! write Hello World
Above I only typed "write" and this says that the file is only inside the "lib" folder, it doesn't has a package to storage and separate it, so it is a Freedom command(A command that doesn't has packages or nodes).
-! console.write Hello World
Now I typed above "console.write" and this says that the file has a package or node to storage and separate it, this means that it is a Tied command(A command that has packages or nodes).
With that, a file is separated from the package(s) with a dot, the more dots you put, more folders will be navigated to find the file and proceed to the next execution.
Code
Finnaly the code. With the import statement I tryied this:
import os
import form
curDir = os.path.dirname(os.path.abspath(__file__)) # Returns the current direrctory open
while __name__ == "__main__":
c = input('Prosser:%s-! ' % (os.getcwd())).split() # Think the user typed "task.kill"
path = c[0].split('.') # Returns a list like: ["task", "kill"]
try:
args = c[1:] # Try get the command arguments
format = form.formater(args) # Just a text formatation like create a new line with "$n"
except:
args = None # If no arguments the args will just turn the None var type
pass
if os.path.exists(curDir + "/lib/" + "/".join(path) + ".py"): # If curDir+/lib/task/kill.py exists
module = __import__("lib." + '.'.join(path)) # Returns "lib.task.kill"
module.exec.main(args) # Execute the "exec" class and the def "**main**"
else:
pathlast = path[-1] # Get the last item, in this case "kill"
path.remove(path[-1]) # Remove the last item, "kill"
print('Error: Unknow command: ' + '.'.join(path) + '. >>' + pathlast + '<<') # Returns an error message like: "Error: Unknow command: task. >>kill<<"
# Reset the input interface
The problem is that when the line "module = __import__("lib." + '.'.join(path))" is executed the console prints the error:
Traceback (most recent call last):
File "/home/pedro/documents/projects/prosser/main.py", line 18, in <module>
module.exec.main(path) # Execute the "exec" class and the def "**main**"
AttributeError: module 'lib' has no attribute 'exec'
I also tried to use:
module = \_\_import\_\_(curDir + "lib." + '.'.join(path))
But it gets the same error. I think it's lighter for now. I'd like if someone help me or find some replacement of the code. :)
I think you have error here:
You have diffirent path here:
if os.path.exists(curDir + "/lib/" + "/".join(path) + ".py")
And another here, you dont have curDir:
module = __import__("lib." + '.'.join(path)) # Returns "lib.task.kill"
You should use os.path.join to build paths like this:
module = __import__(os.path.join(curdir, 'lib', path + '.py'))