I am trying to check for information on Linux server,if it has certain disks named 'ocr'.
So I have run a shell command and capture the output in a text file.
Then I will search for the string in the file.But this below script doest work.
import os
myCmd = os.popen('ls /dev/asm|grep ocr').read()
print(myCmd)
with open('myCmd') as f:
if 'ocr' in f.read():
print("RAC server")
and capture the output in a text file
You've saved it in a string variable, then you're trying to open and read a file named myCmd. These likely have different content because it's not clear where you've actually written any files
You don't need a file for the logic of that code
if 'ocr' in myCmd:
print("RAC server")
Also, you really shouldn't be using shell commands if you don't have to
for f in os.listdir("/dev/asm"):
if "ocr" in f:
print("RAC server")
break
Related
I'm writing an application that requires a text file to automatically pop open (visible to the user client) after a sequence of database processes are completed. At the end of a SQL file, I have an xp_cmdshell command that reads:
exec xp_cmdshell 'C:\mattermark_etl_project\powershell "C:\mattermark_etl_project\open_file.ps1"'
which executes a powershell script that contains the following:
C:\mattermark_etl_project\python.exe "C:\mattermark_etl_project\open_file.py"
The powershell script executes a python script which contains the following:
import os
def openFile():
fileName = C:\mattermark_etl_project\company_data.txt(ACTIVE)
os.system("C:\mattermark_etl_project\notepad.exe" + fileName)
openFile()
Can someone please help me understand why the text file isn't popping open? SSMS returns output stating the commands ran successfully with "null" results.
I am working on Debian Stable Linux which is otherwise working very well. I have following code in a python script file named "myrev" which works to reverse order of lines of given text file:
#! /usr/bin/python3
import sys
if len(sys.argv) < 2:
print("Usage: myrev infile")
sys.exit()
try:
with open(sys.argv[1], "r") as f:
lines = f.read().split("\n")
except:
print("Unable to read infile.")
sys.exit()
lines.reverse()
print("\n".join(lines))
It works properly and prints out reverse order of lines if I use following Linux command
./myrev infile
However, if I try to redirect output with following command to original file, a blank file is generated:
./myrev infile > infile
After above command, infile becomes an empty file.
Why can't I redirect output to original file and how can this be solved?
Using > opens the target file for write, same as if opened via fopen with mode "w". That immediately truncates the file, before your program even launches (it happens while the shell is configuring the environment before execing your program). You can't use this approach to read from a file and replace it as a single step. Best you could do would be something like:
./myrev infile > infile.tmp && mv -f infile.tmp infile
where, if the command succeeds, you complete the work by replacing the original file with the contents of the new file.
I tried looking inside stackoverflow and other sources, but could not find the solution.
I am trying to run/execute a Python script (that parses the data) using a text file as input.
How do I go about doing it?
Thanks in advance.
These basics can be found using google :)
http://pythoncentral.io/execute-python-script-file-shell/
http://www.python-course.eu/python3_execute_script.php
Since you are new to Python make sure that you read Python For Beginners
Sample code Read.py:
import sys
with open(sys.argv[1], 'r') as f:
contents = f.read()
print contents
To execute this program in Windows:
C:\Users\Username\Desktop>python Read.py sample.txt
You can try saving the input in the desired format (line-wise) file, and then using it as an alternative to STDIN (standard input file) using the file subcommand with Python
python source.py file input.txt
Note: To use it with input or source files in any other directory, use complete file location instead of file names.
I have a Python script that runs properly on my laptop, but when running on my raspberry pi, the following code does not seem to be working properly. Specifically, "TextFile.txt" is not being updated and/or saved.
openfile = open('/PATH/TextFile.txt','w')
for line in lines:
if line.startswith(start):
openfile.write(keep+'\n')
print ("test 1")
else:
openfile.write(line)
print ("test 2")
openfile.close()
I am seeing "test 1" and "test 2" in my output, so I know that the code is being reached, paths are correct, etc
It may be due to a permissions problem. I am running the script from the terminal by using:
usr/bin/python PATH/script.py
Python is owned by "root" and script.py is owned by "Michael".
My first guess:
Does the file exist? If it does not exist then you cannot write to it. Try this to create the file if it does not exist: file = open('myfile.dat', 'w+')
Additionally manually opening and closing file handles is bad practice in python. The with statement handles the opening and closing of the resource automatically for you:
with open("myfile.dat", "w+") as f:
#doyourcalculations with the file object here
for line in f:
print line
All, thank you for your input. I was able to figure out that it was writing to the new file, but it was overwriting with the same text. The reason was because ".startswith" was returning false when I expected true. The misconception was due to the difference between how Windows and Unix treat new line characters (/n /r).
Since your code is running, there should be a file somewhere.
You call "PATH/script.py", but there is "/PATH/TextFile.txt" in your program. Is the slash before PATH a mistake? Have you checked the path in your program is really where you are looking for the output file?
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()