how to convert this Python code from sys.args to stdin - python

I used sys.arg instead of stdin but have no idea how to change it
My code creates error when reading the command line :
import sys
from pathlib import Path
import re
text_file = Path(sys.argv[1:])
if text_file.exists() and text_file.is_file():
read = text_file.read_text()
length = len(re.findall(r'[a-zA-Z]+', read))
print(f'{text_file} has', length, 'words')
else:
print(f'File not found: {text_file}')
This is the error that produces while running:
drv, root, parts = self._parse_args(args)
TypeError: expected str, bytes or os.PathLike object, not list
command line argument is - python3 total_words.py < lyrics/Justin_Bieber.txt (have the instructions to run the command line in this way)

Related

Python script that executes another python script

I'm pretty new to the world of python. I decided to do a project but came to a stop, after my script wouldn't execute the right way. In which I mean the script that I need to be executed on its own through another script keeps on giving me nothing or some syntax error instead of all the stuff that is supposed to be happening (converting files). The other script in question writes new lines into the other script to change the file name (to be converted) to the newest file. The file looks something like this:
import glob
import os.path
folder_path = r'C:\User\Desktop\Folder\Audio'
file_type = r'\*mp4'
files = glob.glob(folder_path + file_type)
max_file = max(files, key=os.path.getctime)
mp3_file = max_file.replace('.mp4', '')
with open ("file.py", 'w') as f:
f.write("")
with open ("file.py", 'w') as f:
f.write('from moviepy.editor import *\n' "mp4_file = '{}'\n"
"mp3_file = '{}.mp3'\n" 'videoclip = VideoFileClip(mp4_file)\n' 'audioclip = videoclip.audio\n'
'audioclip.write_audiofile(mp3_file)\n' 'audioclip.close()\n' 'videoclip.close()\n'.format(max_file, mp3_file))
exec(open("file.py").read())
Right now it gives this error:
Traceback (most recent call last):
File "C:\Users\Desktop\Folder\Audio\File Manager.py", line 19, in <module>
exec(open("file.py").read())
File "<string>", line 2
mp4_file = 'C:\User\Desktop\Folder\Audio\test.mp4'
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
I plan not on using that exact line of code to execute my python file since there are many alternatives, but if I was on the right trail, then I might as well. The other file that's supposed to be executed has generic file converting code:
from moviepy.editor import *
mp4_file = 'C:\User\Desktop\Folder\Audio\test.mp4'
mp3_file = 'C:\User\Desktop\Folder\Audio\test.mp3'
videoclip = VideoFileClip(mp4_file)
audioclip = videoclip.audio
audioclip.write_audiofile(mp3_file)
audioclip.close()
videoclip.close()
Other solutions mostly gave me a blank inactive shell; if the answer to this problem that it's impossible, then it might as well be, and I'll take that as a valid answer, but please explain why.
Corrections
You are using different quotes while writing to the file, from single quotes ' to double ", update it to be more consistent.
The error is suggesting that while writing to the file it is also writing some unicode characters which it cannot read hence the unicode error (look at where the carrot ^ is pointing at, it's a blank space since it's not a printable character).
Suggestions
Don't just write to a file and then immediately read from it. Different operating systems have different behaviour for such repeated access which will give you strange issues (this is not your issue tho)
Just create a function extractMp3FromVideoFile which takes two arguements max_file and mp3_file
Instead of writing to a file and increasing the HDD IO simply put the file's code into a variable and then exec it.
Solution
import glob
import os.path
folder_path = r'C:\User\Desktop\Folder\Audio'
file_type = r'\*mp4'
files = glob.glob(folder_path + file_type)
max_file = max(files, key=os.path.getctime)
mp3_file = max_file.replace('.mp4', '')
code = "from moviepy.editor import *\nmp4_file = '{}'\nmp3_file = '{}.mp3'\nvideoclip = VideoFileClip(mp4_file)\naudioclip = videoclip.audio\naudioclip.write_audiofile(mp3_file)\naudioclip.close()\nvideoclip.close()\n".format(max_file, mp3_file)
exec(code)

Define type for fileinput.input file object

I am trying to find & replace in file using below code snippet:
from pathlib import Path
import fileinput
import re
TEXT_FILE_PATH = Path.cwd() / "temp.txt"
FIND_PUBLIC_PATH_REGEX = r"(publicPath: ').*(',)"
REPLACE_PUBLIC_PATH_REGEX = r"\1/\2"
with fileinput.input(TEXT_FILE_PATH, inplace=True) as file:
for line in file:
print(re.sub(FIND_PUBLIC_PATH_REGEX, REPLACE_PUBLIC_PATH_REGEX, line), end="")
The problem is I am getting type error on last line which says:
No overloads for "sub" match the provided arguments
Argument types: (Literal['(publicPath: \').*(\',)'], Literal['\\1/\\2'], AnyStr#input)Pylance(reportGeneralTypeIssues)
I can't understand why I am getting this error.
Regards.

Unable to convert image format in python

I am trying to convert all my images in a file into jpg format, defined as 'a' but I keep getting error as cannot convert. Any help?
from PIL import Image
import matplotlib.pyplot as plt
import os
#import imtools
#path = imtools.get_imlist('.')
a = 'K:\wq'
for infile in os.listdir(a):
outfile = os.path.splitext(infile)[0] + ".jpg"
if infile != outfile:
try:
Image.open(infile).save(outfile)
except OSError as error:
print ("cannot convert", infile)
error log:
cannot convert manojcasual.png
Process finished with exit code 0
os.listdir() returns the name of the files, without the path.
Unless the files are in your current working directory, you must give the complete path to open them. You can use os.path.join() for that.
Also, note that some sequences like '\n' are parsed as special characters in ordinary strings. This can be a problem on Windows, if any of the escape sequences appears in the path, as in 'C:\new'.
To avoid problems, you should always write your literal paths as raw strings (r'.....') to tell Python not to interpret these sequences.
So, your code should look like:
from PIL import Image
import matplotlib.pyplot as plt
import os
a = r'K:\wq' # notice the r'...'
for infile in os.listdir(a):
outfile = os.path.splitext(infile)[0] + ".jpg"
if infile != outfile:
try:
Image.open(os.path.join(a, infile)).save(os.path.join(a, outfile))
except OSError as error:
print ("cannot convert", infile)

Python - reference a file in a different directory

I have to reference a file that exists in a different directory. This is just a text file, not a python module. I've read countless posts, most of which are about including modules. Nothing that I read is giving me a successful answer. Out of many attempts, this is my latest:
import os
REMOTE_FILE = open(os.path.join('/Users/me/Dropbox/otherfolder', 'text.txt'), "r")
decrypted = subprocess.check_output(['openssl', 'aes-128-cbc', '-d', '-in', REMOTE_FILE, '-base64', '-pass', key])
The program doesn't fail on this line immediately, but when I attempt to reference this file I get:
TypeError: Can't convert '_io.TextIOWrapper' object to str implicitly
What am I doing wrong? Thanks!
Use REMOTE_FILE = os.path.join('/Users/me/Dropbox/otherfolder', 'text.txt') instead to get only the file path as a string and not an file object.
Your REMOTE_FILE is a file object, not a string. Given your code, you probably meant to do:
import os
REMOTE_FILE = os.path.join('/Users/me/Dropbox/otherfolder', 'text.txt')
decrypted = subprocess.check_output(['openssl', 'aes-128-cbc', '-d', '-in', REMOTE_FILE, '-base64', '-pass', key])
Keeping REMOTE_FILE as a string, not an object.

Error when opening txt file in Python

I have to work with a txt file and to do that I used the following code:
inputFile = open("C:/Abaqus_JOBS/Job-M1-3_4.inp", "r") #CAE INPUT FILE
However I get this error when I ran this line in a specific application for running python scripts available in another program. I don't get any error when I ran it in Spyder.
TypeError: an integer is required
I don't have a clue why this error occurs....
EDIT:
lines of code until line in question
import os
from os import *
from abaqus import *
from odbAccess import *
from abaqusConstants import *
import time
import itertools
os.chdir('C:\\Abaqus_JOBS')
LCKf = 'C:\\Abaqus_JOBS\\Job-M1-3_2.lck'
STAf = 'C:\\Abaqus_JOBS\\Job-M1-3_2.sta'
def get_num_part(s):
for i in xrange(len(s)):
if s[i:].isdigit():
return s[i:]
return ''
if not path.exists(LCKf):
time.sleep(1)
while path.exists(LCKf) and path.isfile(LCKf) and access(LCKf, R_OK):
variableX = 0
else:
odb = openOdb(path='Job-M1-3_2.odb')
#get CF
#session.odbs[name].steps[name].frames[i].FieldOutput
myAssembly = odb.rootAssembly
myAssemblyName = odb.rootAssembly.name
nsteps=len(odb.steps.values())
step1 = odb.steps.values()[nsteps-1]
step1Name = odb.steps.values()[nsteps-1].name
myInstanceName = odb.rootAssembly.instances.values()[0].name
dCF3=[]
dCF3v=[]
coordFv=[]
fileData = [] #array with the input file
nodes = [] #array with the content of *NODES
inputFile = open("C:/Abaqus_JOBS/Job-M1-3_4.inp", "r") #CAE INPUT FILE
#fileData = variable with all the lines of the inp file
for line in inputFile:
fileData.append([x.strip() for x in line.split(',')])
the error is:
Traceback (most recent call last):
File "c:/Abaqus_JOBS/results.py", line 47, in <module>
inputFile = open("C:/Abaqus_JOBS/Job-M1-3_4.inp", "r") #CAE INPUT FILE
TypeError: an integer is required
With the
from os import *
You're importing all os stuff in the global namespace, including os.open(). Don't do this.
The second argument, flags, is defined as integer constants while you're providing a single-character string r. This is basically what DSM was telling you and what Lattyware said.
open() included in Python by default in the global namespace, which you were expecting apparently, is different:
Note: This function is intended for low-level I/O. For normal usage,
use the built-in function open(), which returns a “file object” with
read() and write() methods (and many more). To wrap a file descriptor
in a “file object”, use fdopen().

Categories

Resources