How to save cmd output to text file through another script python - python

I am able to save the cmd data onto a text file using the following command:
python code_3.py > output.txt
However I am calling code_3.py from primary_script.py by writing:
import code_3
os.system('loop3.py')
But I want it to perform the functionality of the what the previous line does. This doesn't work:
os.system('loop3.py > opt.txt ')
Can someone please tell me what to do?

Here's how to do it with the subprocess module:
import subprocess
import sys
p1 = subprocess.Popen([sys.executable, "loop3.py"], stdout=subprocess.PIPE)
output, err = p1.communicate()
with open('opt.txt', 'w') as file:
file.write(output.decode())

Related

Unable to read file with python

I'm trying to read the content of a file with python 3.8.5 but the output is empty, I don't understand what I'm doing wrong.
Here is the code:
import subprocess
import os
filename = "ls.out"
ls_command = "ls -la"
file = open(filename, "w")
subprocess.Popen(ls_command, stdout=file, shell=True)
file.close()
# So far, all is ok. The file "ls.out" is correctly created and filled with the output of "ls -la" command"
file = open(filename, "r")
for line in file:
print(line)
file.close()
The output of this script is empty, it doesn't print anything. I'm not able to see the content of ls.out.
What is not correct here ?
Popen creates a new process and launches it but returns immediately. So the end result is that you've forked your code and have both processes running at once. Your python code in executing faster than the start and finish of ls. Thus, you need to wait for the process to finish by adding a call to wait():
import subprocess
import os
filename = "ls.out"
ls_command = "ls -la"
file = open(filename, "w")
proc = subprocess.Popen(ls_command, stdout=file, shell=True)
proc.wait()
file.close()
file = open(filename, "r")
for line in file:
print(line)
file.close()
Popen merely starts the subprocess. Chances are the file is not yet populated when you open it.
If you want to wait for the Popen object to finish, you have to call its wait method, etc; but a much better and simpler solution is to use subprocess.check_call() or one of the other higher-level wrappers.
If the command prints to standard output, why don't you read it drectly?
import subprocess
import shlex
result = subprocess.run(
shlex.split(ls_command), # avoid shell=True
check=True, text=True, capture_output=True)
line = result.stdout

execute code in files without importing them in python

def main():
print('writing multiple lines in a file through user input')
infile=open("xyz.txt", "w")
for line in iter(input, ''):
infile.write(line + '\n');
infile.close()
infile=open("xyz.txt", "r")
for line in infile:
print(line)
infile.close()'
if __name__ == "__main__":
main()
This is the main program and i have attached the output file as well which i want the output to be executed.output
You can execute a python file by invoking a python subprocess:
import subprocess
subprocess.call(['python3', 'xyz.txt'])
This will run python3 and execute the script in the "xyz.txt" file. This code has only been tested on Linux/Mac, so if you are on windows you may have to put the full path to python3 where it is installed - haven't tested, sorry.
Use the inbuilt os library
import os
os.system("python other_file.py")
This way you can use any commands from the os environment, so the possibilities are not limited to python.
But if you would like to read the output of the given script you subprocess instead
import subprocess
output = subprocess.check_output("python 2.py", shell=True)
print(output)

Why does subprocess command print 0 instead of path?

I'm beginner in python
I have tried following code. When I run code it doesn't give error, however expected output must be in file, instead it prints output on console.
In actual test.txt file it make entries as 0.
Why does it print 0 and not the path returned by pwd command?
from subprocess import call
path = call('pwd')
with open('test.txt', "w") as f :
f.seek(0)
f.write(str(path))
f.close()
If you want to get output from an external command, use subprocess.check_output as noted by #Paul Rooney. You may change your program as follows to print the output of pwd to file:
from subprocess import check_output
path_bytes = check_output('pwd', shell=True)
path_str = path_bytes.decode('utf-8')
with open('test.txt', 'w') as f:
f.write(path_str)

python run .exe app with argument

If i write this in command prompt:
"senna-win32.exe < input.txt >output.txt"
it works perfect but i need to do this from python code, how is this possible?
I have tried:
import subprocess
subprocess.call([pathToExe, "input.txt" , "output.txt"])
import subprocess
subprocess.call([pathToExe, '< input.txt > output.txt'])
I'm getting error of "invalid argument
< input.txt > output.txt".
Thank you Jack!!!
import subprocess
myinput = open('in.txt')
myoutput = open('out.txt', 'w')
p = subprocess.Popen('senna-win32.exe', stdin=myinput, stdout=myoutput)
p.wait()
myoutput.flush()

Module require to be run two times to produce result

I am trying to display a output from system . But, my script produces the result only when I run it two times. Below is the script. Using subprocess.Popen at both the places does not produce any out put and same with subprocess.call.
#!/usr/bin/env python
import subprocess
import re
contr = 0
spofchk='su - dasd -c "java -jar /fisc/dasd/bin/srmclient.jar -spof_chk"'
res22 = subprocess.call("touch /tmp/logfile",shell=True,stdout=subprocess.PIPE)
fp = open("/tmp/logfile","r+")
res6 =subprocess.Popen(spofchk,shell=True,stdout=fp)
fil_list=[]
for line in fp:
line = line.strip()
fil_list.append(line)
fp.close()
for i in fil_list[2:]:
if contr % 2 == 0:
if 'no SPOF' in i:
flag=0
#print(flag)
#print(i)
else:
flag = 1
else:
continue
#Incrementing the counter by 2 so that we will only read line with spof and no SPOF
contr+=2
The child process has its own file descriptor and therefore you may close the file in the parent as soon as the child process is started.
To read the whole child process' output that is redirected to a file, wait until it exits:
import subprocess
with open('logfile', 'wb', 0) as file:
subprocess.check_call(command, stdout=file)
with open('logfile') as file:
# read file here...
If you want to consume the output while the child process is running, use PIPE:
#!/usr/bin/env python3
from subprocess import Popen, PIPE
with Popen(command, stdout=PIPE) as process, open('logfile', 'wb') as file:
for line in process.stdout: # read b'\n'-separated lines
# handle line...
# copy it to file
file.write(line)
Here's a version for older Python versions and links to fix other possible issues.
Since subprocess open a new shell , so in first time it is not possible to create the file and the file and write the output of another subprocess at the same time
.. So only solution for this is to use os. System ..

Categories

Resources