I have following the link:
to incorporate a command line command into my python script and it is working fine.
but i want o run the command over all the files present in a folder. How to send the file name to the command line? I think there should be some for loop but I cant hit the chord. Also I wnat to save the result in a .csv file.
import os
import subprocess
list_files = subprocess.run(["file","my_audio.wav"])
How to ?
for file_name in folder
output=subprocess.run(["file","file_name"])`
save output in .csv
Got the answer !
import os
import subprocess
import glob
with open("bit_rate.csv", "w") as fp:
for file_name in glob.glob('./*.wav'):
print(file_name)
subprocess.run(["file",file_name ], stdout=fp)
Related
I'm using python for a school project and i want to know how create a simple virus with simple this effect
i tried this:
How do I use shutil to make a python file copy itself after doing a calculation?
and this:
https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-script-from-another-script
then i didn't know how to run the second copy
the code example(I WANT TO RUN THE COPY FOR ONCE)
import os
import shutil
##############
print("hello world")
shutil.copy(__file__, "copy.py") # Copies the file
exec(open("copy.py").read())# Executes the copied file if it is in the same directory as the other file
You can run the second file with execfile(File Path)
So you got something like
import os
import shutil
import fileinput
##############
print("hello world")
shutil.copy(__file__, "copy.py") # Copies the file
file = [Path of the copied File]
for line in fileinput.FileInput(file, inplace=1):
if "execfile('copy.py')" in line:
line=line.rstrip()
line=line.replace(line,"")
print (line,end="")
# This could get a problem with large files but should work properly with small files
execfile('copy.py') # Executes the copied file if it is in the same directory as the other file
# Else give it the directory where the file is stored (with / instead of \)
so i get it (i have posted in reddit too)
link: https://www.reddit.com/r/learnpython/comments/lxupy9/how_to_make_a_python_file_copy_itself_then/
import shutil
import subprocess
import os
import random
print("hello world")
new_file_name = str(random.randint(1, 10000)) + ".py"
shutil.copy(__file__, new_file_name)
subprocess.call((new_file_name), shell=True)
I've been trying to figure this out for hours with no luck. I have a list of directories that have subdirectories and other files of their own. I'm trying to traverse through all of them and move all of their content to a specific location. I tried shutil and glob but I couldn't get it to work. I even tried to run shell commands using subprocess.call and that also did not work either. I understand that it didn't work because I couldn't apply it properly but I couldn't find any solution that moves all contents of a directory to another.
files = glob.glob('Food101-AB/*/')
dest = 'Food-101/'
if not os.path.exists(dest):
os.makedirs(dest)
subprocess.call("mv Food101-AB/* Food-101/", shell=True)
# for child in files:
# shutil.move(child, dest)
I'm trying to move everything in Food101-AB to Food-101
shutil module of the standart library is the way to go:
>>> import shutil
>>> shutil.move("Food101-AB", "Food-101")
If you don't want to move Food101-AB folder itself, try using this:
import shutil
import os
for i in os.listdir("Food101-AB"):
shutil.move(os.path.join("Food101-AB", i), "Food-101")
For more information about move function:
https://docs.python.org/3/library/shutil.html#shutil.move
Try to change call function to run in order to retrieve the stdout, stderr and return code for your shell command:
from subprocess import run, CalledProcessError
source_dir = "full/path/to/src/folder"
dest_dir = "full/path/to/dest/folder"
try:
res = run(["mv", source_dir, dest_dir], check=True, capture_output=True)
except CalledProcessError as ex:
print(ex.stdout, ex.stderr, ex.returncode)
I would like to loop over files using subprocess.run(), something like:
import os
import subprocess
path = os.chdir("/test")
files = []
for file in os.listdir(path):
if file.endswith(".bam"):
files.append(file)
for file in files:
process = subprocess.run("java -jar picard.jar CollectHsMetrics I=file", shell=True)
How do I correctly call the files?
shell=True is insecure if you are including user input in it. #eatmeimadanish's answer allows anybody who can write a file in /test to execute arbitrary code on your machine. This is a huge security vulnerability!
Instead, supply a list of command-line arguments to the subprocess.run call. You likely also want to pass in check=True – otherwise, your program would finish without an exception if the java commands fails!
import os
import subprocess
os.chdir("/test")
for file in os.listdir("."):
if file.endswith(".bam"):
subprocess.run(
["java", "-jar", "picard.jar", "CollectHsMetrics", "I=" + file], check=True)
Seems like you might be over complicating it.
import os
import subprocess
path = os.chdir("/test")
for file in os.listdir(path):
if file.endswith(".bam"):
subprocess.run("java -jar picard.jar CollectHsMetrics I={}".format(file), shell=True)
I am trying to execute several python code at the same time in different folder using concurrent futures. The code run fine but when i check the subfolders I don't see any output so I am assuming the python code that I am calling were never executed.
The code first find a python script with specific name in all of the folders then call them in parallel. The write the output in another text file so my goal is to have them write the text file in folders that the script is located.
for example:
Folder A
ReadTextFileV9-10.py
Folder B
ReadTextFileV9-10.py
I want the out put to be
Folder A
ReadTextFileV9-10.py
Output.txt
Folder B
ReadTextFileV9-10.py
Output.txt
This is my code.
from concurrent import futures
import re
import os
import timeit
import os
import glob
import re
from glob import glob
import subprocess
FileList = [];
start_dir = os.getcwd();
pattern = "ReadTextFileV9-10.py"
for dir,_,_ in os.walk(start_dir):
FileList.extend(glob(os.path.join(dir,pattern))) ;
print(FileList)
def Run_Code(Str):
return subprocess.run(Str)
futuress=[]
def main_function(FileList):
with futures.ProcessPoolExecutor(max_workers=2) as executor:
#results = executor.map(Run_Code, FileList)
for file in FileList:
future = executor.submit(subprocess.run, file)
futuress.append(future)
return futuress
results=main_function(FileList)
I appreciate if any one can help me figure out what I am doing wrong.
Thanks
Okay so I'm basically writing a program that creates text files except I want them created in a folder that's in this same folder as the .py file is that possibly? how do I do it?
using python 3.3
To find the the directory that the script is in:
import os
path_to_script = os.path.dirname(os.path.abspath(__file__))
Then you can use that for the name of your file:
my_filename = os.path.join(path_to_script, "my_file.txt")
with open(my_filename, "w") as handle:
print("Hello world!", file=handle)
use open:
open("folder_name/myfile.txt","w").close() #if just want to create an empty file
If you want to create a file and then do something with it, then it's better to use with statement:
with open("folder_name/myfile.txt","w") as f:
#do something with f