I would like a variable to be stored in .py file and be imported into a main Python program.
Let me explain the problem in code. In my home folder I have the following files:
testcode.py
testmodule.py
testcode contains the following code:
import pprint
while __name__ == '__main__':
import testmodule
variableFromFile=testmodule.var
print("Variable from file is "+str(variableFromFile))
print("Enter variable:")
variable=input()
Plik=open('testowymodul.py','w')
Plik.write('var='+variable)
Plik.close()
and testmodule contains:
var=0
Now when I launched testcode.py, and input as variables 1,2,3,4,5 I got the following output:
Variable from file is 0
Enter variable:
1
Variable from file is 0
Enter variable:
2
Variable from file is 0
Enter variable:
3
Variable from file is 0
Enter variable:
4
Variable from file is 0
Enter variable:
5
Variable from file is 0
Enter variable:
But I would like to refresh this variable every time it is printed on screen, so I expect in this line:
print("Variable from file is "+str(variableFromFile))
to update the variable's value. Instead, I get in output only the first value of the variable, so the program print 0 every time. Only restarting the program will refresh the value of var.
Is there a way to import variables from file, change them at runtime and then then use their updated values later on in the script?
I believe your basic problem stems from the use of the variable in the testmodule.py file. As written you code imports this file and thus the pyhton interpreter assigns the value of testmodule.var to the contents thyat exist at load time. The code which attempts to update the variable isn't working the way you intended, since Plik.write('var='+variable) is creating a text string of the form "var = n". Thus subsequent attempts to import the testmodule and get the testmodule.var variable will result in a 0 value.
To fix this problem, as suggested by #JONSG, requires you abandon the import context and do something along the lines of the following:
#Contents of testmodule.txt file
0
#Contents of the testcode.py file
def readVar(fn):
with open(fn, 'r') as f:
return f.read().strip()
def writeVar(fn, val):
with open(fn,'w') as f:
f.write(val)
def runcode():
varfile = 'testmodule.txt' #Assumes testmodule.txt is in same folder as code
variableFromFile= readVar(varfile)
print("Variable from file is "+str(variableFromFile))
variable=input("Enter variable: ")
writeVar(varfile, variable)
def main():
runcode()
if __name__ == "__main__":
main()
Now every time you run the file, the latest variable data will be loaded and then updated with a new value.
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?
is there way to make "code template" in visual studio code?
All I want after creating new file is to fill the file with this code here like c# does...
This can save me time
# Imports
x = 10
# Set Variables
def main(text, number, variable):
print("Hello, world..", text, number, variable)
# Main function
if __name__ == "__main__":
main("xyz", 5, x)
Unfortunately, there is no option to do this in IDLE. You will have to type it in manually.
I see that you want to open a file with a code already written on it.
For that purpose you can use the following code:
f = open("myfile.py", "w") # This will create a file.
f.write('''
# Imports
x = 10
# Set Variables
def main(text, number, variable):
print("Hello, world..", text, number, variable)
# Main function
if __name__ == "__main__":
main("xyz", 5, x)
''')
f.close()
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
I am writing a simple python program which allows us to list all video files in a directory and play them according to the user input. However, I am getting an list out of range error while running this code.
Code:
import os
from subprocess import Popen
def processFile(currentDir):
# Get the absolute path of the currentDir parameter
currentDir = os.path.abspath(currentDir)
global list
list=[]
filesInCurDir = os.listdir(currentDir)
# Traverse through all files
for file in filesInCurDir:
curFile = os.path.join(currentDir, file)
# Check if it's a normal file or directory
if os.path.isfile(curFile):
# Get the file extension
curFileExtension = curFile[-3:]
# Check if the file has an extension of typical video files
if curFileExtension in ['avi', 'dat', 'mp4', 'mkv', 'vob']:
# We have got a video file! Increment the counter
processFile.counter += 1
list.append('curFile')
# Print it's name
print(processFile.counter, file)
else:
# We got a directory, enter into it for further processing
processFile(curFile)
if __name__ == '__main__':
# Get the current working directory
currentDir = os.getcwd()
print('Starting processing in %s' % currentDir)
# Set the number of processed files equal to zero
processFile.counter = 0
# Start Processing
processFile(currentDir)
# We are done. Exit now.
print('\n -- %s Movie File(s) found in directory %s --' \
% (processFile.counter, currentDir))
print('Enter the file you want to play')
x = int(input())
path = list[x-1]
oxmp=Popen(['omxplayer',path])
Aha, found your problem.
In processFile, you say
def processFile(currentDir):
# ...
global list
list=[]
# ...
processFile(...)
This means that, whenever you recurse, you are clearing the list again! This means that the processFile.counter number becomes out-of-sync with the actual length of list.
Three notes on this:
Storing variables on a function like processFile.counter is generally frowned upon, AFAIK.
There's no need for a separate counter; you can simply put len(list) to find the number of entries in your list.
To fix the list problem itself, consider initializing the list variable outside of the function or passing it in as a parameter to be modified.