So, I'm working on a personal project. I made two python scripts using youtube-dl to download a song and a thumbnail, respectively. The script for the song downloads the song as an .mp3 file with a custom name (designated by an argument). The script for the thumbnail downloads the .webp file of the thumbnail with a custom name (designated by an argument) and converts it to png and then jpg. I put these two into functions and in different folders, like this.
yt2mp3 -- youtubeMP3.py
__main__.py
thumbnails.py -- __main__.py
downloadimg.py
The full scripts can be found at this github repo: https://github.com/ignition-ctrl/yt2mp3
The code is not pretty but it works. However, the issue is this. I have a function in my .bashrc called downloadmusic(). It'll take two arguments, the link and the custom filename and run the python script youtubeMP3.py with the arguments. The youtubeMP3.py has the function download_music() and within that function it has a reference to the function download_thumbnail from downloadimg.py. My problem is that from my terminal, I can see that it runs download_thumbnail twice. Once when starting the script, and then after running download_music(). I only want it to run after download_music(). The code is supposed to only run in this code.
determiner = input("Do you want to download the thumbnail?")
if determiner == "yes" or "y" or "Yes":
downloadimg.download_thumbnail(str(ytname), str(filename))
else:
exit(0)
That's the only reference to the download_thumbnail, but I can see the terminal output from download_thumbnail() before the print statements I put in download_music(). I also get two copies of the jpg file that comes from download_thumbnail(). I've been scratching my head about this all day. If anyone could help, I'd appreciate it.
First time download_thumbnail() is called when you import the module. It tries to run
try:
download_thumbnail(sys.argv[1], sys.argv[2])
except IndexError:
raise NameError("Please provide a link and your desired filename")
you can wrap this inside an if statement like this
if __name__ == '__main__':
try:
download_thumbnail(sys.argv[1], sys.argv[2])
except IndexError:
raise NameError("Please provide a link and your desired filename")try:
download_thumbnail(sys.argv[1], sys.argv[2])
so that this block will run only when the file is executed directly, not when importing.
Related
I have registered with exercism.io on the Python track, and haven't got off to a good start! The first exercise is a simple print hello world example, and I am of course able to write the code that executes this. The problem I have is where on earth do I place my code? Should I overwrite the existing hello_world.py file with my own file, or add my script lines to the existing file? I have read the documentation and must be missing something as I can't fathom out what to do with my code to test and submit.
When I download the test material, there is a default hello.world.py file created in the relevant directory, which contains this;
def hello():
pass
There is also a hello_world_test.py that contains this;
import unittest
import hello_world
# Tests adapted from `problem-specifications//canonical-data.json` # v1.1.0
class HelloWorldTest(unittest.TestCase):
def test_hello(self):
self.assertEqual(hello_world.hello(), 'Hello, World!')
if __name__ == '__main__':
unittest.main()
I have written a file called exercism_hello_world.py which contains this;
# This script prints "Hello, World!" to the console
print ("Hello, World!")
# end of script
Can anyone who may already be using exercism.io please advise how / where I place my code so that I can test / submit the first exercise and continue with the learning. Thanks.
After installing the cli script.
Enter the file location of full python file along with the name of the file.
Example
exercism submit C:\Users\srag\Exercism\python\hello-world\hello_world.py
You want the Exercism directory to begin with a capital "E" if you're running on macOS.
Try out:
exercism submit /Users/(your username)/Exercism/python/hello-world/hello_world.py
You should add your solution to the hello_world.py file.
However, you can change the default Exercism workspace directory. If you are on MacOS or Unix you can do that via terminal:
exercism configure --workspace="YOUR_PATH"
By changing this setting, everytime you run the command to "clone" the problem, it will get copied to the path you specified.
Regarding this problem, I am not sure if it helps, but it was stated to return "Hello, World!" and not print it.
I made this small program :
I wanna know how to automatically call it, so that when I open the .py it shows up immediatly.
Please understand that I am a beginner in Python.
The right way to do this is to add the following statement in the end of the file:
if __name__ == "__main__":
table_par_7()
Explanation
This will ensure that if you open the file directly (and thus makes it the main file), the function will run, but if another python file imports this file (thus this file isn't the main one), it wont run.
You can call it like this:
# Add this lines at the end of your code
table_par_7()
If you mean:- (1) When you will run the .py file, how to call it. Then the answer is, you will have to write the name of function and press ENTER to execute it.
(2) When you will open the .py file from any folder, is it possible to print final result. The the answer is a big NO. This is because using def in any program is just a keyword to create function. It do not have any property by which it will execute by its own. It must be called by the system which is known as system call.
Note:- Wait before you mark my question as duplicate please read it completely.
I wan't to run a python file using another.
I have tried using runpy,os.system & subprocess. The problem with subprocess and os.system command is that it fails for systems which have python2 and python3 both installed if i just run with python. If i run it with python3 i fails for people having single installation.
The problem with runpy is that it does not work according to my needs.
The following is run my directory structure
test\
average\
average.py
average_test.py
many similar directories like average...
run_tests.py
The content of average is
def average(...args):
# Do something
The content of average_test.py
from average import average
def average_test():
assert average(1,2,3) == 2
Now if i use runpy.run_path it throws a ImportError saying average is not a module. The os.system and subprocess.call works perfectly but I hope my "testing_framework" will be used by many so I can't use the above two functions. Isn't there any other way to do it. I have researched the whole of SO and google but didn't find a solutions.
Also sys.path.append/insert will not help as I can't tell my "users" to add this to every file of theirs.
Is there no easy way to do it? I mean like pytest accomplishes this so there must be a way.
Thank you moderators for reading my question.
EDIT I forgot to mention that I wan't the code to be run in if __name__ == '__main__' block too and I have also tried using a snippet from another SO answer which fails too. The snippet was
def exec_full(filepath):
global_namespace = {
"__file__": filepath,
"__name__": "__main__",
}
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), global_namespace)
Please note that the directory structure was just an example the user may have a different code/directory structure.
NOTE:- I found the answer. I needed to do subprocess.call([sys.executable,file_path]). sys.executable returns the path for the python executable file for the current version.
Create an empty __init__.py in average folder
And then try to import
from average import average
it would work like charm :)
test\
average\
average.py
average_test.py
__init__.py
many similar directories like average...
run_tests.py
I couldn't fine solution for this question using search option so my question is:
I have a script that does the job but only for one file. Just to explain what`s going on here:
import sys
sys.path.append('C:\Program Files\FME\fmeobjects\python27')
import fmeobjects
runner = fmeobjects.FMEWorkspaceRunner()
workspace = 'C:\FME\Project_1.fmw'
parameters = {}
parameters['SourceDataset_ACAD'] ='C:\AutoCAD\Project_1.dwg'
parameters['DestDataset_OGCKML'] ='C:\Maps_KMZ\Project_1.kmz'
runner.runWithParameters(workspace, parameters)
try:
# Run Workspace with parameters set in above directory
runner.runWithParameters(workspace, parameters)
# or use promptRun to prompt for published parameters
#runner.promptRun(workspace)
except fmeobjects.FMEException as ex:
# Print out FME Exception if workspace failed
print ex.message
else:
#Tell user the workspace ran
print('The Workspace is ran successfully'.format(workspace))
runner = None
This script executes FMW file that does conversion from AutoCAD DWG (C:\AutoCAD) to KMZ file and stores it in C:\Maps_KMZ folder. Now, I need to do the same thing for about 20-ish FME files that are in the same source folder.
Is it possible to execute each file at the time and add specific time frame between two executions let`s say 2 minute pause between them, because I can not run 2 or more conversions at the same time, it would crash Windows.
Thank you very much for your help!
I suggest that you modify your script to use command line arguments. You can either use sys.argv directly for a very simple interface or the parseargs module for more complex options.
You can write the interface to accept individual files names or directory names. To traverse the files of a directory, look at os.walk().
I am very new to python, but I have written a simple python script tool for automating the process of updating mosaic datasets at my job. The tool runs great, but sometimes I get the dreaded 9999999 error, or "the geodatase already exists" when I try to overwrite the data.
The file structure is c:\users\my.name\projects\ImageryMosaic\Alachua_2014\Alachua_2014_mosaic.gdb. After some research, I determined that the lock was being placed on the FGDB whenever I opened the newly created mosaic dataset inside of the FGDB to check for errors after running the tool. I would like to be able to overwrite the data instead of having to delete it, so I am using the arcpy.env.overwriteOutput statement in my script. This works fine unless I open the dataset after running the tool. Since other people will be using this tool, I don't want them scratching thier heads for hours like me, so it would be nice if the script tool could look for the presence of a .Lock file in the geodatabase. That way I could at least provide a statement in the script as to why the tool failed in lieu of the unhelpful 9999999 error. I know about arcpy.TestSchemaLock, but I don't think that will work in this case since I am not trying to place a lock and I want to overwrite the FGDB, not edit it.
Late but this function below will check for lock files in given (gdb) path.
def lockFileExist(path = None):
if path == None:
import traceback
raise Exception("Invalid Path!")
else:
import glob
full_file_paths = glob.glob(path+"\\*.lock")
for f in full_file_paths:
if f.endswith(".lock"):
return True
return False
if lockFileExist(r"D:\sample.gdb"):
print "Lock file found in gdb. Aborting..."
else:
print "No lock files found!. Ready for processing..."