I am trying to pass an argument from batch file to my python file.
I followed the steps given in these two links:
Passing Argument from Batch File to Python
Sending arguments from Batch file to Python script
Here is a part of my python file where I'm trying to pass argument:
def main(argv):
imapServ = 'imap.gmail.com'
filename = 'TestRunLog.log'
attachment = open("{} {}".format(argv[0], filename), 'rb')
....##rest of the code
import sys
try:
if __name__ == '__main__':
print 'go ahead'
main(sys.argv[:1])
except ImportError:
print 'hi'
Also, here is the part of batch file which I'm using to send argument to the Python file:
c:\python27\python.exe C:\Users\abcd\Documents\automation\testsendemail.py %%myhome%\Documents\automation\Testresults\%resultDir%
pause
Above, %resultDir% is the variable which is generated based on timestamp.
Here is the output:
go ahead
Traceback (most recent call last):
C:/Users/abcd/Documents/automation/testsendemail.py\TestRunLog.log
File "C:/Users/abcd/Documents/automation/testsendemail.py", line 44, in <module>
main(sys.argv[:1])
File "C:/Users/abcd/Documents/automation/testsendemail.py", line 25, in main
attachment = open("{} {}".format(argv[0], filename), 'rb')
IOError: [Errno 2] No such file or directory: 'C:/Users/abcd/Documents/automation/testsendemail.py TestRunLog.log'
I followed lots of stackoverflow questions regarding this issue but still I'm unable to run. Not sure where the mistake is.
The issue is related on how python works with argv.
In this scenario, when you run:
main(sys.argv[:1]) # (["C:\Users\abcd\Documents\automation\testsendemail.py"])
you actually get only the first arguments passed to the python script, which is the current script location.
To get all the arguments but the first, you must fix that array filter:
main(sys.argv[1:]) # ["%%myhome%\Documents\automation\Testresults\%resultDir%"])
Note that the second filter will also include any other arguments that you might add to the command line.
Also, as a side note. You should consider using the STD lib to join the paths.
It should be something like this:
from os.path import join
(...)
filename = 'TestRunLog.log'
attachment = open(join(argv[0], filename), 'rb')
Related
I'm currently trying to write a simple Python (3.6.6) program that can grab a Youtube video, play it back, and graph the waveplot and spectogram of the file. But it only runs properly in Jupyter notebook. I'm using this site as a guide on the program. I want to make sure it can run in IDLE as well, but so far no luck. Here's the code section regarding the file retrieval / path set and trying to play it back:
# Downloading audio
audiostream = video.getbestaudio()
# audiostream.download()
from tkinter import filedialog as fd
# Asking where to save it
print("Select the directory...")
dir_name = fd.askdirectory()
print(dir_name)
path = dir_name + "/" + video.title + ".wav"
print(path)
audiofile = audiostream.download(filepath=path)
import IPython.display as ipd
# Playing back the audio
print("Playing back audio...")
ipd.Audio(filename=path)
And the error message:
Traceback (most recent call last):
File "C:\Users\(myPCname)\Desktop\YTpyDwnlder.py", line 45, in <module>
ipd.Audio(filename=path)
File "C:\Python36\lib\site-packages\IPython\lib\display.py", line 110, in __init__
super(Audio, self).__init__(data=data, url=url, filename=filename)
File "C:\Python36\lib\site-packages\IPython\core\display.py", line 627, in __init__
self.reload()
File "C:\Python36\lib\site-packages\IPython\lib\display.py", line 121, in reload
super(Audio, self).reload()
File "C:\Python36\lib\site-packages\IPython\core\display.py", line 652, in reload
with open(self.filename, self._read_flags) as f:
OSError: [Errno 22] Invalid argument: 'C:/Users/(myPCname)/Desktop/gui/Low Roar - "I\'ll Keep Coming".wav'
The path seems correct for the most part so I'm not sure why the program thinks it's wrong. I've tried to double and triple check through looking up other sites on Python string formatting for files and I can't find what's wrong. I've also tried inserting '\' to all potential single or double quotes within (provided they don't already have the '\' before them) the string but it still doesn't like it (I know this is a futile attempt and is redundant).
How can I fix this?
Also sorry if the tags are incorrect; this is my first time posting a question on here.
Nevermind. I found that the problem was due to invalid characters in the filename ('"' is changed to '#' in the filename).
I'm using Python Version 2.7.10 with macOS Sierra 10.12.16 and Xcode 8.3.3
In the demo program I want to write 2 lines of text in a file.
This should be done in two steps. In the first step the method openNewFile() is called. The file is created with the open command and one line of text is written to the file. The file handle is the return value of the method.
In the second step the method closeNewFile(fH) with the file handle fH as input argument is called. A second line of text should be written to the file and the file should be closed. However, this leads to an error message:
Traceback (most recent call last):
File "playground.py", line 23, in <module>
myDemo.createFile()
File "playground.py", line 20, in createFile
self.closeNewFile(fH)
File "playground.py", line 15, in closeNewFile
fileHandle.writelines("Second line")
ValueError: I/O operation on closed file
Program ended with exit code: 1
It seems to me that handling the file over from one method to another could be the problem.
#!/usr/bin/env python
import os
class demo:
def openNewFile(self):
currentPath = os.getcwd()
myDemoFile = os.path.join(currentPath, "DemoFile.txt")
with open(myDemoFile, "w") as f:
f.writelines("First line")
return f
def closeNewFile(self, fileHandle):
fileHandle.writelines("Second line")
fileHandle.close()
def createFile(self):
fH = self.openNewFile()
self.closeNewFile(fH)
myDemo = demo()
myDemo.createFile()
What are I doing wrong?
How can this problem be fixed?
You're mistaken about what with....as does. This code is the culprit here:
with open(myDemoFile, "w") as f:
f.writelines("First line")
return f
Just before the return, with closes the file, so you end up returning a closed file from the function.
I should add -- opening a file in one function and returning it without closing it (what your actual intention is) is major code smell. That said, the fix to this problem would be to get rid of the with...as context manager:
f = open(myDemoFile, "w")
f.writelines("First line")
return f
An improvement to this would be to not get rid of your context manager, but to carry out all your I/O within the context manager. Don't have separate functions for opening and writing, and don't segment your I/O operations.
I've been adapting an old piece of code to be Python 3 compliant and I came across this individual script
"""Utility functions for processing images for delivery to Tesseract"""
import os
def image_to_scratch(im, scratch_image_name):
"""Saves image in memory to scratch file. .bmp format will be read
correctly by Tesseract"""
im.save(scratch_image_name, dpi=(200, 200))
def retrieve_text(scratch_text_name_root):
inf = file(scratch_text_name_root + '.txt')
text = inf.read()
inf.close()
return text
def perform_cleanup(scratch_image_name, scratch_text_name_root):
"""Clean up temporary files from disk"""
for name in (scratch_image_name, scratch_text_name_root + '.txt',
"tesseract.log"):
try:
os.remove(name)
except OSError:
pass
On the second function, retrieve_text the first line fails with:
Traceback (most recent call last):
File ".\anpr.py", line 15, in <module>
text = image_to_string(Img)
File "C:\Users\berna\Documents\GitHub\Python-ANPR\pytesser.py", line 35, in image_to_string
text = util.retrieve_text(scratch_text_name_root)
File "C:\Users\berna\Documents\GitHub\Python-ANPR\util.py", line 10, in retrieve_text
inf = file(scratch_text_name_root + '.txt')
NameError: name 'file' is not defined
Is this a deprecated function or another problem alltogether? Should I be replacing file() with something like open()?
In Python 2, open and file are mostly equivalent. file is the type and open is a function with a slightly friendlier name; both take the same arguments and do the same thing when called, but calling file to create files is discouraged and trying to do type checks with isinstance(thing, open) doesn't work.
In Python 3, the file implementation in the io module is the default, and the file type in the builtin namespace is gone. open still works, and is what you should use.
You can do what the documentation for file() suggests -
When opening a file, it’s preferable to use open() instead of invoking this constructor directly.
You should use open() method instead.
I'm attempting to write a very simple script that counts the number of entries/files a given ZIP file has, for some statistics.
I'm using the zipfile library, and I'm running into this problem where the library appears not to support .zipx format.
bash-3.1$ python zipcount.py t.zipx
Traceback (most recent call last):
File "zipcount.py", line 10, in <module>
zipCount(file)
File "zipcount.py", line 5, in zipCount
with ZipFile(file, "r") as zf:
File "c:\Python34\lib\zipfile.py", line 937, in __init__
self._RealGetContents()
File "c:\Python34\lib\zipfile.py", line 978, in _RealGetContents
raise BadZipFile("File is not a zip file")
zipfile.BadZipFile: File is not a zip file
Googling for help reveals that the zipx format is not the same as zip, and so maybe I shouldn't be expecting this to work. Further googling though fails to bring up a library that actually can deal with zipx. Searching stack overflow didn't find much either.
I can't possibly be the only person who wants to manipulate zipx files in python, right? Any suggestions?
chilkat might work for this. It's not a free library but there is a 30 day trial. Here is an example from http://www.example-code.com/python/ppmd_compress_file.asp:
import sys
import chilkat
compress = chilkat.CkCompression()
# Any string argument automatically begins a 30-day trial.
success = compress.UnlockComponent("30-day trial")
if (success != True):
print "Compression component unlock failed"
sys.exit()
compress.put_Algorithm("ppmd")
# Decompress back to the original:
success = compress.DecompressFile("t.zipx", "t")
if (success != True):
print compress.lastErrorText()
sys.exit()
print "Success!"
The API documentation: http://www.chilkatsoft.com/refdoc/pythonCkCompressionRef.html
There is no direct python package to unzip the zipx files in python.
So, One simple way to unzip it is using subprocess and winzip application. Please find the below code.
import subprocess
command = "C:\Program Files\WinZip\wzunzip.exe" "D:\Downloads\hello.zipx" "D:\unzip_location"
subprocess.run(command, shell=True, timeout=120)
Is it possible to use the maya.cmds instead of using any maya API to load/import in a file format in which it is not part of Maya file types?
I have tried googling but to no avail results other than the fileDialog command in Maya, otherwise it would means I will need to implement maya API (where I totally do not have any experiences with it)
I tried the following:
multipleFilters = "chan (*.chan)"
fileList = cmds.fileDialog2(fileMode=1, fileFilter=multipleFilters, dialogStyle=2)
if not fileList:
# return or print something or bail out early
filename = fileList[0]
cmds.file(filename, i=True)
Instead I keep getting the following error:
# Error: Unrecognized file.
# Traceback (most recent call last):
# File "<maya console>", line 3, in <module>
# RuntimeError: Unrecognized file. #
Any ideas?
cmds.file only works for files with translators that are registered via the API, either in Python or C++.
You can, however, easily write python (or even mel) scripts which read files off disk and create stuff in your scenes. You can use cmds.fileDiialog2 to present a file dialog to the user to pick file off disk, but it will be up to you to read the file.
multipleFilters = "chan (*.chan)"
fileList = cmds.fileDialog2(fileMode=1, fileFilter=multipleFilters, dialogStyle=2)
with open (fileList[0], 'rt') as filehandle:
for line in filehandle:
print line # or do something useful with the data