execute code in files without importing them in python - 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)

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

How to save cmd output to text file through another script 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())

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 ..

How to execute a python script and write output to txt file?

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

How to simulate sys.argv[1:] on web based python

I have a Python program where the initiation script looks like this:
if __name__ == "__main__":
main(sys.argv[1:])
To run this, I have to use Shell or Terminal like this:
myscript somefile.xml
The script accepts a file and then does all the rest of the work.
Now, I am trying to run this program on a web server.
SO I use a HTML Form to submit the file to this script.
In my Python script, I am doing like this:
....
elif req.form.has_key("filename"):
item=req.form["filename"]
if item.file:
req.write("I GO HERE")
myscript.main(item)
....
As you can see here, I am trying to send the file directly to the "main" function.
Is this the right way to do?
I dont get any script error, but the Python script is not producing the expected results.
Any help?
Thanks
Write the uploaded file contents to a temporary file (using tempfile.mkstemp()) and pass the filename of the temporary file into main() wrapped in a list.
For example (untested):
import os
import tempfile
fd, temp_filename = tempfile.mkstemp()
try:
with os.fdopen(fd, "wb") as f:
# Copy file data to temp file
while True:
chunk = item.file.read(100000)
if not chunk: break
f.write(chunk)
# Call script's main() function
myscript.main([temp_filename])
finally:
os.remove(temp_filename)

Categories

Resources