I'm currently creating a script that will simply open a program in the SAME directory as the script. I want to have a text file named "target.txt", and basically the script will read what's in "target.txt" and open a file based on its contents.
For example.. The text file will read "program.exe" inside, and the script will read that and open program.exe. The reason I'm doing this is to easily change the program the script opens without having to actually change whats inside.
The current script Im using for this is:
import subprocess
def openclient():
with open("target.txt", "rb") as f:
subprocess.call(f.read())
print '''Your file is opening'''
Its giving me an error saying it cannot find target.txt, even though I have it in the same directory. I have tried taking away the .txt, still nothing. This code actually worked before, however; it stopped working for some strange reason. I'm using PythonWin compiler instead of IDLE, I don't know if this is the reason.
There are two possible issues:
target.txt probably ends with a newline, which messes up subprocess.call()
If target.txt is not in the current directory, you can access the directory containing the currently executing Python file by parsing the magic variable __file__.
However, __file__ is set at script load time, and if the current directory is changed between loading the script and calling openclient(), the value of __file__ may be relative to the old current directory. So you have to save __file__ as an absolute path when the script is first read in, then use it later to access files in the same directory as the script.
This code works for me, with target.txt containing the string date to run the Unix date command:
#!/usr/bin/env python2.7
import os
import subprocess
def openclient(orig__file__=os.path.abspath(__file__)):
target = os.path.join(os.path.dirname(orig__file__), 'target.txt')
with open(target, "rb") as f:
subprocess.call(f.read().strip())
print '''Your file is opening'''
if __name__ == '__main__':
os.chdir('foo')
openclient()
Related
I am trying to collect every txt file from my computer and write it into the terminal when I run the script. I do not know how to do it. Is there a way to read every txt file in the computer then print the contents? (not a certain folder or directory).
In Python, the glob module would give you a list of filenames matching a given string. In your case, glob.glob('dir/*.txt') would give you a list of filenames in directory dir that end in .txt. You can then open each file and print() it to the terminal. Depending on your OS, you might be able to do it in your terminal without writing a separate script.
I am trying to run python script inside my load script in Qlik Sense app.
I know that I need to put OverrideScriptSecurity=1 in Settings.ini
I put
Execute py lib://python/getSolution.py 100 'bla'; // 100 and 'bla' are parameters
and I get no error in qlik sense, but script is not executed (I think) because inside the script I have
f = open("file.xml", "wb")
f.write(xml)
f.close
and file is not saved.
If I run script from terminal, then script is properly executed.
What could go wrong?
By the way, my full path to python interpreter is
C:\Users\Marko Z\AppData\Local\Programs\Python\Python37-32\python.exe
EDIT :
Even if I add this
Set vPythonPath = "C:\Users\Marko Z\AppData\Local\Programs\Python\Python37-32\python.exe";
Set vPythonFile = "C:\Users\Marko Z\Documents\Qlik\Sense\....\getSolution.py";
Execute $(vPythonPath) $(vPythonFile);
I get the same behaviour. No error, but not working,...
I even see that if I change path (incorrect path) it give me an error, but incorrect file it doesn't give me an error.... (but I am sure it is the right file path...)
My python code is
xml = "Marko"
xml = xml.encode('utf-8')
f = open("C:\\Users\\Marko Z\\Test.xml", "wb")
f.write(xml)
f.close
I figure out what was wrong.
For all others that would have similar problems:
Problem is in space in path.
If I move my script in c:\Windows\getSolution.py it work. I also need to change the python path to c:\Windows\py.exe
so end script looks like:
Execute c:\Windows\py.exe c:\Windows\getSolution.py 100 'bla';
But I still need to figure how to work with space in path...
Strange. With exactly the same python file and QS script the result file is generated correctly.
The content of my settings.ini.
[Settings 7]
StandardReload=0
OverrideScriptSecurity=1
According to Qlik's documentation there should be an empty line at the end (point 4 from the lists)
I was able to get the below to work in qlik sense:
set vPyExe = C:\Program Files\Python37\python.exe;
set vPyScript = D:\...\PythonScript.py;
Execute
"$(vPyExe)" "$(vSource)"
;
Instead of opening all the programs and files one by one to edit my website when I turn on my computer, I want to execute a python script to open them all for me. However, when I run it, it is always opening an index.html file in a folder titled 'index'. I want it to open up say, webpages.html in the 'webpages' folder.
#!/usr/bin/env python
import os, webbrowser, subprocess
os.chdir('C:/Users/Bruin/Desktop/My_Webpage')
current_path = os.getcwd()
file_to_open = input('What filename to open?')
print("hello")
#subprocess.call([r'C:\Users\Bruin\AppData\Local\atom\atom.exe', r'C:\Users\Bruin\Desktop\My_Webpage\'' + file_to_open + r'\'' + file_to_open + r'.html'])
subprocess.call([r'C:\Users\Bruin\AppData\Local\atom\atom.exe', r'C:\Users\Bruin\Desktop\My_Webpage\webpages\webpage.html'])
webbrowser.open('file:///C:/Users/Bruin/Desktop/My_Webpage/index/index.html', new=2)
I commented out where I used the inputed variable because even explicitly typing in what I want to open directly into the script, it is not working. It is opening up in the browser just fine.
I am also working in PyCharm, do not know if that matters. It didn't work in IDLE either. I'm lost on where to go.
I am doing an assignment on text formatting and alignment (text wrapping) and I need to write my formatted string to new file. But once I have written to the file (or think I've written) where does that file go? Does it actually create a file on my desktop or am I being stupid?
This is my code:
txtFile = open("Output.txt", "w")
txtFile.write(string)
txtFile.close()
return txtFile
Cheers,
JT
The text is written to a file called "Output.txt" in your working directory (which is usually the directory from which the script has been executed).
To display the working directory, you can use:
>>> import os
>>> os.getcwd()
'/home/adam'
When you open a file without specifying a file path, the file will be created in the python scripts working directory.
Usually that is the location of your script but there are times when it may be a different place.
The os module in python will provide functions for checking and changing the working directory within python itself.
most notably:
os.chdir(path)
os.fchdir(fd)
os.getcwd()
It will create a new file called "Output.txt" in the same directory that you executed your script from. It may mean that the file can't be written to, if you're in a directory that doesn't have the appropriate permissions for your user.
try:
directoryListing = os.listdir(inputDirectory)
#other code goes here, it iterates through the list of files in the directory
except WindowsError as winErr:
print("Directory error: " + str((winErr)))
This works fine, and I have tested that it doesnt choke and die when the directory doesn't exist, but I was reading in a Python book that I should be using "with" when opening files. Is there a preferred way to do what I am doing?
You are perfectly fine. The os.listdir function does not open files, so ultimately you are alright. You would use the with statement when reading a text file or similar.
an example of a with statement:
with open('yourtextfile.txt') as file: #this is like file=open('yourtextfile.txt')
lines=file.readlines() #read all the lines in the file
#when the code executed in the with statement is done, the file is automatically closed, which is why most people use this (no need for .close()).
What you are doing is fine. With is indeed the preferred way for opening files, but listdir is perfectly acceptable for just reading the directory.