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()
Related
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)
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())
I have below code :
import os, subprocess
def cfile():
p = r'/mypath/abc'
cmd = ["who am i | awk '{print $1}'"]
if not os.path.exists(p):
fh = open(p, 'a')
try:
subprocess.Popen(cmd, stdout=fh)
finally:
fh.close()
cfile()
above code is creating the file called 'folder' but not writing anything. Can you please help me to get to know what is wrong here. I am using python 2.7
You could call .wait() on each Popen object in order to be sure that it's finished and then call flush(). Maybe something like this:
import os
import subprocess
def cfile():
p = r'/mypath/abc'
cmd = ["who am i | awk '{print $1}'"]
fh = open(p, 'a+')
try:
sb = subprocess.Popen(cmd, shell=True, universal_newlines=True, stdout=fh)
sb.wait()
fh.flush()
finally:
fh.close()
cfile()
I'm trying to do something like the following to print 3 and 4:
input.txt
1
2
3
4
program1.py
import subprocess
inputfile = open('input.txt', 'r')
inputfile.readline()
inputfile.readline()
subprocess.call('python program2.py',stdin=inputfile)
inputfile.close()
program2.py
while True:
print raw_input()
It will print nothing. But if I remove the readlines() it will print 1 through 4 just fine.
How can I use a file starting at a certain line for a stdin for a subprocess?
You can use Popen() and .communicate() instead of call() . I am not completely sure why call() does not work in your case, but the following would work -
program1.py
import subprocess
import sys
inputfile = open('input.txt', 'r')
inputfile.readline()
inputfile.readline()
p = subprocess.call(['python', 'program2.py'],stdin=subprocess.PIPE,stdout=sys.stdout)
p.communicate(inputfile.read())
inputfile.close()
.decode() is needed as communicate() expects byte string, not normal string. I also redirected the stdout for the process to the stdout of your script, so that the results are printed. Also, a better way to write program2.py is -
import sys
for l in sys.stdin:
print l
This does not cause program2.py to go into infinite loop.
Example/Demo -
I have two files, a.py and b.py -
a.py -
import subprocess
import sys
inputfile = open('input.txt', 'r')
inputfile.readline()
inputfile.readline()
p = subprocess.Popen(['/usr/bin/python', 'b.py'],stdin=subprocess.PIPE,stdout=sys.stdout)
p.communicate(inputfile.read())
inputfile.close()
b.py -
import sys
for l in sys.stdin:
print l
Result of running a.py -
3
4
I'm executing a .py file, which spits out a give string. This command works fine
execfile ('file.py')
But I want the output (in addition to it being shown in the shell) written into a text file.
I tried this, but it's not working :(
execfile ('file.py') > ('output.txt')
All I get is this:
tugsjs6555
False
I guess "False" is referring to the output file not being successfully written :(
Thanks for your help
what your doing is checking the output of execfile('file.py') against the string 'output.txt'
you can do what you want to do with subprocess
#!/usr/bin/env python
import subprocess
with open("output.txt", "w+") as output:
subprocess.call(["python", "./script.py"], stdout=output);
This'll also work, due to directing standard out to the file output.txt before executing "file.py":
import sys
orig = sys.stdout
with open("output.txt", "wb") as f:
sys.stdout = f
try:
execfile("file.py", {})
finally:
sys.stdout = orig
Alternatively, execute the script in a subprocess:
import subprocess
with open("output.txt", "wb") as f:
subprocess.check_call(["python", "file.py"], stdout=f)
If you want to write to a directory, assuming you wish to hardcode the directory path:
import sys
import os.path
orig = sys.stdout
with open(os.path.join("dir", "output.txt"), "wb") as f:
sys.stdout = f
try:
execfile("file.py", {})
finally:
sys.stdout = orig
If you are running the file on Windows command prompt:
python filename.py >> textfile.txt
The output would be redirected to the textfile.txt in the same folder where the filename.py file is stored.
The above is only if you have the results showing on cmd and you want to see the entire result without it being truncated.
The simplest way to run a script and get the output to a text file is by typing the below in the terminal:
PCname:~/Path/WorkFolderName$ python scriptname.py>output.txt
*Make sure you have created output.txt in the work folder before executing the command.
Use this instead:
text_file = open('output.txt', 'w')
text_file.write('my string i want to put in file')
text_file.close()
Put it into your main file and go ahead and run it. Replace the string in the 2nd line with your string or a variable containing the string you want to output. If you have further questions post below.
file_open = open("test1.txt", "r")
file_output = open("output.txt", "w")
for line in file_open:
print ("%s"%(line), file=file_output)
file_open.close()
file_output.close()
using some hints from Remolten in the above posts and some other links I have written the following:
from os import listdir
from os.path import isfile, join
folderpath = "/Users/nupadhy/Downloads"
filenames = [A for A in listdir(folderpath) if isfile(join(folderpath,A))]
newlistfiles = ("\n".join(filenames))
OuttxtFile = open('listallfiles.txt', 'w')
OuttxtFile.write(newlistfiles)
OuttxtFile.close()
The code above is to list all files in my download folder. It saves the output to the output to listallfiles.txt. If the file is not there it will create and replace it with a new every time to run this code. Only thing you need to be mindful of is that it will create the output file in the folder where your py script is saved. See how you go, hope it helps.
You could also do this by going to the path of the folder you have the python script saved at with cmd, then do the name.py > filename.txt
It worked for me on windows 10