Open a shell file and replace a sting inside it using python - python

Here I transfer a shell script from my sytem to raspberry pi using ssh and run the script on Rpi
python3 paswd.py | scp replace.py pi#192.168.1.$i:
python3 paswd.py |ssh -tt pi#192.168.1.$i 'chmod u+x ~/'replace.py' && exit'
This happens and it shows no errors
Replace.py
def replace():
fout=open("launch.sh","rt")
for line in fout:
fout.close
fout=open("launch.sh","wt")
fout.write(line.replace('chromium-browser','chromium-browser --kiosk '))
fout.close
replace()
launch.sh
echo "connected, launching browser"
chromium-browser & disown
After the replace.py is executed am not geting the require results, I get an empty launch.sh or no changes at all. As said it shows no errors. Please let me know where is my mistake. The saame code worked perfectly for .txt file, it replaces "chromium-browser" with "chromium-browser --kiosk" but on .sh file am not getting it.
Thanks for the help

This will solve your problem.
def replace():
file_path = "launch.sh"
find = "chromium-browser"
replacement = "chromium-browser --kiosk"
with open(file_path) as f:
s = f.read()
s = s.replace(find, replacement)
with open(file_path, "w") as f:
f.write(s)
replace()

Related

Py2app can't read files

I want to read from a file with a python application. Here is my source code.
MyApplication.py:
if __name__ == '__main__':
fin = open("/absolute/path/to/file.txt", "r")
fin.readline()
fin.close()
setup.py:
# Copied and pasted it from their docs
from setuptools import setup
setup(
app=["MyApplication.py"],
setup_requires=["py2app"],
)
Then I try to run python setup.py py2app and everything goes smoothly, however when I open the app a popup appears saying "MyApplication Error".
Is there a way for me to solve this or at least get more information about what's happening?
EDIT FOR MORE CLARITY:
The line that is causing problems is fin.readline(). Also, writing to files works, and reading a file that the app itself has created doesn't generate errors. This code, for example, works.
if __name__ == '__main__':
fout = open("/absolute/path/to/newfile.txt", "a+")
fout.write("Test\n")
fout.close()
fin = open("/absolute/path/to/newfile.txt", "r")
line = fin.readline()
fin.close()
fout = open("/absolute/path/to/newfile.txt", "a+")
fout.write("Line read: " + line)
fout.close()
The output file will show:
Test
Line read: Test
I found this hint veeery useful:
“right click -> Show Packages -> Resources -> Mac OS”, and execute your app directly do help, because it shows specific errors on the console
Source: http://uxcrepe.com
It might help you a lot, as it shows you typical python errors you are already familiar with!
Enjoy!
It was the encoding, because of course it was. Just open the file like this.
fin = open("/absolute/path/to/file.txt", "r", encoding="utf-8")

Raspberry Pi: Python Script doesn't work if autostarted with lxterminal but if started with geany it works just fine. What could be my mistake?

I have a program that's autostarted everytime when my raspberry boots and it should upload data to an API, but everytime it tries to connect it gets an error. I use requests to post my request and it works perfectly fine if i start the program in Geany but i should manage to start it with LXTerminal.
i have already tried to change the python version its started in but it doesn't work and i have tried to change the path.
class CSVDataModel:
red = 0
green = 0
def job():
with open('/path/data.csv', "r") as f:
reader = csv.reader(f, delimiter = ",")
data = list(reader)
ifile = open('/path/data.csv', "r")
reader = csv.reader(ifile, delimiter = ";")
a = []
for row in reader:
a.append(row)
payload = CSVDataModel()
payload.red = int(a[0][0])
payload.green = int(a[1][0])
url ="url"+"red="+str(payload.red)+"&green="+str(payload.green)
print(url)
time.sleep(5)
r = requests.post(url, timeout = 5)
print("sent")
with open("/path/data.csv", "w") as csvFile:
writer = csv.writer(csvFile, delimiter= ' ', lineterminator='\r\n')
writer.writerow("0")
writer.writerow("0")
csvFile.close()
print("reset")
schedule.every(1).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
In the comments, you said:
the window closes instantly after it gets an error and i am unable to read what it says
You you've set it up to run Python in a terminal window somehow?
What you should do instead is open a terminal window, cd to the directory where your script is stored and run python <scriptname>.py (or maybe python3 <scriptname>.py).
Doing it like that should give you a backtrace of the error in the terminal window.
Instead of running Python in a terminal window you could e.g. run it from your crontab file, and capture standard output and standard error streams to a file:
python scriptname.py >logfile.txt 2>&1
That would allow for automation and error capture.
The reason it works in Geany and doesn't from LXTerminal is quite possibly the fact that geany is running your script from the working directory, i.e. the one in which your relative paths correctly resolve. Try either using absolute paths (i.e. /home/user/path/data.csv) instead of relative ones or use os.chdir() in the script to make sure the working directory is always the correct one.

How to open .bashrc in python

I have a problem with opening the .bashrc file in python. I have written the following code:
mydata = open ('/home/lpp/.bashrc', 'r')
and I get this:
$ /usr/bin/python2.7 /home/lpp/lpp2016/Handin3.py
Process finished with exit code 0
Python does not open the file .bashrc. What did I do wrong?
This is an old question. I went through the same problem and this is my solution to read the content.
with open('.bashrc', 'r') as content:
fileContent = content.read()
print(fileContent)
fp = open(os.path.join((os.path.expanduser('~'), '.bashrc'))
fp.read()
it is opening and reading all the content

Using subprocess to log print statements of a command

I am running a Transporter command, which prints a log of what is happening to the prompt.
How would I re-direct all the print statements to a separate file called transporter_log.txt in the same folder as the script is running from? Something like -
log_file = open(PATH, 'w')
subprocess.call(shlex.split("/usr/local//iTMSTransporter -m verify...")
log_file.write(...)
You could specify the file as stdout parameter:
with open(PATH, 'wb') as log_file:
subprocess.check_call(cmd, stdout=log_file)
The output of cmd is written to log_file.
What about using the redirect command (in on unix)?
your_python.py > /path/to/transporter_log.txt

how to direct output into a txt file in python in windows

import itertools
variations = itertools.product('abc', repeat=3)
for variations in variations:
variation_string = ""
for letter in variations:
variation_string += letter
print (variation_string)
How can I redirect output into a txt file (on windows platform)?
From the console you would write:
python script.py > out.txt
If you want to do it in Python then you would write:
with open('out.txt', 'w') as f:
f.write(something)
Obviously this is just a trivial example. You'd clearly do more inside the with block.
You may also redirect stdout to your file directly in your script as print writes by default to sys.stdout file handler. Python provides a simple way to to it:
import sys # Need to have acces to sys.stdout
fd = open('foo.txt','w') # open the result file in write mode
old_stdout = sys.stdout # store the default system handler to be able to restore it
sys.stdout = fd # Now your file is used by print as destination
print 'bar' # 'bar' is added to your file
sys.stdout=old_stdout # here we restore the default behavior
print 'foorbar' # this is printed on the console
fd.close() # to not forget to close your file
In window command prompt, this command will store output of program.py into file output.txt
python program.py > output.txt
If it were me, I would use David Heffernan's method above to write your variable to the text file (because other methods require the user to use a command prompt).
import itertools
file = open('out.txt', 'w')
variations = itertools.product('abc', repeat=3)
for variations in variations:
variation_string = ""
for letter in variations:
variation_string += letter
file.write(variation_string)
file.close()
you may use >>
log = open("test.log","w")
print >> log, variation_string
log.close()
Extension to David's answer
If you are using PyCharm,
Go to Run --> Edit Configurations --> Logs --> Check mark Save console
output to file --> Enter complete path --> Apply

Categories