Reputation: 149
I'm using this code os.system("dcapgen.exe C:\\Users\\folder\\a.dcap")
in my python script to run this command dcapgen.exe C:\Users\folder\a.dcap. This command generates .txt file in its current directory. I want to use this generated .txt file further in my code. How to do this? I don't want command log output. Thanks!
I'm new to python programming.
Upvotes: 0
Views: 81
Reputation: 149
This cannot be done because .txt file that will be generated is not getting traced in command prompt. we can only get cmd log output using subprocess which is being suggested by other answers. so, we can get access to the generated file by using its path and full name which we know because its naming follows some pattern and location is fixed, like this
generated_text_file = original_file_name+"_some_addition.txt"
with open(generated_text_file, 'r') as file1:
s = file1.read().replace('/n','')
Upvotes: 0
Reputation: 42107
Use subprocess.run
to run the command and capture STDOUT to get the output from the command:
proc = subprocess.run(['dcapgen.exe', 'C:\\Users\\folder\\a.dcap'], stdout=subprocess.PIPE, text=True)
Now you can get the STDOUT from the stdout
attribute:
proc.stdout
You might need to strip-off CR-LF from end:
proc.stdout.rstrip()
Edit:
If you're using Python 2.7, you can use subprocess.check_output
:
out = subprocess.check_output(['dcapgen.exe', 'C:\\Users\\folder\\a.dcap'])
Upvotes: 1
Reputation: 427
Let's assume you have a simple C program that writes "Hello World" to a text file, called text.txt
, as follows:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE * fp = fopen ("text.txt","w");
fprintf(fp, "Hello world\n");
fclose(fp);
return 0;
}
Compiling the C program will give you an executable, in our case it will be called a.out
. The command ./a.out
will run the executable and print to file.
Now let's assume we have a Python script in the same folder. In order to execute the C program AND read from file you'll have to do something like this
import os
# Run the C generated executable
os.system('./a.out')
# At this point a `text.txt` file exists, so it can be accessed
# The "r" option means you want to read. "w" or "a" for write and append respectively
# The file is now accesible with assigned name `file`
with open("text.txt", "r") as file:
file.read() # To get the full content of the file
file.readline() # To read a single line
for line in file: # Handy way to traverse the file line by line
print(line)
EDIT(s) If you want to follow through keep in mind that:
Upvotes: 1
Reputation: 2696
Try the open
method: here.
It is especially handy in Python that you can surround this method with a with
clause.
Upvotes: 1