First of all this is not homework, I'm in a desperate need for a script that will do the following, my problem is, I've never had to deal with python before so I barely know how to use it - and I need it to launch unit tests in TeamCity via a commandline build runner
What I need exactly is :
a *.bat file that will run the script
a python script that will :
get all *_test.exe files in the current working directory
run all the files which were the result of the search
Best regards
import glob, os
def solution():
for fn in glob.glob("*_text.exe"):
os.startfile(fn)
If you copy this into a file, the script should do as you asked.
import os # Access the operating system.
def solution(): # Create a function for later.
for name in os.listdir(os.getcwd()):
if name.lower().endswith('_test.exe'):
os.startfile(name)
solution() # Execute this inside the CWD.
Related
Hello everyone : I have only one folder under my current directory and I want to go to it by running "cd $(ls)".
So I write this code
import os
os.system("cd $(ls)")
But this did not work for me . Anyone can help to write python syntax to go under the only available folder.
PS : the name of the folder is changeable that's why I want to use "cd $(ls)"
The OS module has some utility functions to achieve what you want to do.
os.listdir(): return a list with all files/directories inside the current working directory
os.chdir(path): changes your working directory
So, you could apply these like:
os.chdir(os.listdir()[0])
It is not obvious if by "go to it" you mean "change current directory for the remaining part of script code" or "change directory to be in after the script exits". If the later, you won't be able to do it - os.system starts a subshell, and changes of current directory in a subshell are not propagated to the parent shell. If the former, you should just use:
import glob, os
os.chdir(glob.glob('*')[0])
Use instead:
os.chdir(os.listdir('.')[0])
Although os.system("cd %(ls)) is correctly working in your shell it will not change the current working directory of your running python interpreter, because os.system() is using a separate shell instance that will be destroyed directly after the execution of the cd shell command.
Double check by executing os.getcwd() before and after (os.getcwd() returns the current working directory of your python interpreter).
I have created Tensorflow image classifier and image classifier should be called using another python script.
I tried os.system() but I cant just call Tensorflow scripts coz it's depends on the multiple files in the Tensorflow script location. so I have to include all the files with classifier script in the main script(2nd python script).
What is the best way to do this?
when script is running :
script error when running from another location :
Do you have tried Python Subprocess instead of os.system?
From How do you use subprocess.check_output() in Python? you can see this simple demo:
py2.py:
import sys
print sys.argv
py3.py:
import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)
Running it:
$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"
UPDATE:
I think your problem it that you need to specify/set the correct folder path before running your python script. For example:
Consider you have the following folder structure:
/root/project/script.py
/root/project/data/file.txt
If in your python script you load a file using a relative path like ./data/file.txt, you need to run your script inside the project folder.
If you run it in the root folder, like this:
/root$ python project/script.py
the script fails, because it tries to find the data/file.txt inside the root folder.
You can use the cd command to change the current directory before running your python script. You can do it while calling the os.system, like this:
os.system("cd project && python script.py") # for my example case
whereever you call your python script from, all relative paths in your script will be based on. i.e. you called the script from its project folder in the first image, so the links to project_folder/tf_files/... were working, whereas you lateron called it from elsewhere, so that the symbolic links were messed up. your script tried to find elsewhere/tf_files/... but that subfolder does not exist.
you could edit the script so all paths are always abolute (starting with /home/...), then there is no way of confusing the
I currently have a Python scrip that runs through all Excel files in the current directory and generates a PDF report.
It works fine now but I don't want the users to be anywhere near frozen Python scripts. I created an MSI with cxFreeze which puts the EXE and scripts in the Program Files directory.
What I would like to be able to do is create a shortcut to this executable and pass the directory the shortcut was run from to the Python program so that can be set as the working directory. This would allow the user to move the shortcut to any folder of Excel files and generate a report there.
Does Windows send the location of a opened shortcut to the executable and is there a way to access it from Python?
When you launch a shortcut, Windows changes the working directory to the directory specified in the shortcut, in the Start in field. At this point, Windows has no memory of where the shortcut was stored.
You could change the Start in field to point to the directory that the shortcut is in. But you'd have to do that for every single shortcut, and never make a mistake.
The better approach is to use a script, rather than a shortcut. Place your actual Python script (which we'll call doit.py for sake of example) somewhere in your PYTHONPATH. Then create a single-line Python script that imports it:
import doit
Save it (but don't name it doit.py) and copy it to each directory from which you want to be able to invoke the main script. In doit.py you can use os.getcwd() to find out what directory you're being invoked from.
You could also do it with a batch file. This is a little more flexible in that you can specify the exact name of the script and which Python interpreter should be used, and don't need to store the script in a directory in PYTHONPATH. Also, you don't need to worry about the file's name clashing with the name of a Python module. Simply put this line in a file:
C:\path\to\your\python.exe C:\path\to\your\script.py
Save it as (e.g.) doit.bat and copy it into the directories from which you want to invoke it. As before, your Python script can call os.getcwd() to get the directory. Or you can write it so your Python script accepts it as the first argument, and write your batch file like:
C:\path\to\your\python.exe C:\path\to\your\script.py %cd%
Another thing you can do with the batch file approach is add a pause command to the end so that the user is asked to press a key after the script runs, giving them the opportunity to read any output generated by the script. You could even make this conditional so that it only happens if an error occurs (which requires returning a proper exit code from the script). I'll leave that as an exercise. :-)
Is there a problem with modifying the script to take the directory to process as a command line argument?
You could then configure the different shortcuts to pass in the appropriate directory.
Type the following into a batch file (i.e. script.bat):
python \absolute\path\to\your\script.py %~dp0
pause
Then add these imports at the top of your python file script.py (if not already included):
import os
import sys
And add this to the bottom of the python file (or combine it with a similar statement):
if __name__ == "__main__":
# set current working directory:
if len(sys.argv) > 1:
os.chdir(sys.argv[1])
main()
replace main() with whatever function you want to call or code you want to run.
The following is how I came to my answer:
I tried using kindall's answer and had the following issues:
The first suggestion of storing the script somewhere in PYTHONPATH could not be applied to my situation because my script will be used on a server and needs to be independent of the client computer's python environment (besides having the required pip installations).
I tried calling my python script from a Windows Batch File which could be moved to a different location. Instead of the batch file's location being used as the current working directory, it was C:\Windows.
I tried passing %cd% as an argument to my python script, then setting that to be my CWD. This still resulted in a CWD of C:\Windows.
After reviewing the comments, I tried Eryk Sun's suggestion of instead passing %~dp0 as an argument to the python script. This resulted in the CWD being correctly set to the batch file's location.
I hope this helps others facing similar difficulties.
My coworker is having trouble with a Python install. When running the code below, from 'C:\my\folder\', 'C:\' is returned instead of the current working directory. When I or anyone else run the script on our systems, we get 'C:\my\folder\'.
We're assuming that some global setting must be causing the issue, so I've had the person uninstall Python, delete the local Python2.7 folder, clean the registry and reinstall the Python, but it's still not working.
NOTE: We have a large number of legacy scripts, so revising all of them to use subprocess is impractical. :(
Any ideas?
Environment: Windows XP, Python 2.7
import os
#
# This test script demonstrates issue on the users computer when python invokes
# a subshell via the standard os.system() call.
#
print "This is what python thinks the current working directory is..."
print os.getcwd()
print
print
print "but when i execute a command *from* python, this is what i get for the current working directory"
os.system('echo %cd%')
raw_input()
you could also try something like this
os.chdir("C:\\to\\my\\folder")
print os.system("echo %CD%")
raw_input()
also to get the current working directory i use a different approach
cur_dir = os.path.abspath(".")
os.getcwd() isn't guarenteed to get the location of your script when it is called. Your coworker might be calling the script a different way or his computer (for some reason) handles the current working directory differently.
To get the actual script location you should use the following:
import os
os.path.dirname(os.path.realpath(__file__))
As an example I wrote getcwd and the above line in the same script and ran it from C:\.
Results:
C:\>python C:\Users\pies\Desktop\test.py
C:\Users\pies\Desktop
C:\
It depends on what your real purpose for this script is, whether you actually need the current working directory, or just the current scripts directory. As a little caveat this call will return a different directory if you call a script from script which then uses this call.
os.system("cd dir;command params")
To clarify, the Python module I'm writing is a self-written .py file (named converter), not one that comes standard with the Python libraries.
Anyways, I want to somehow overload my function such that typing in
converter file_name
will send the file's name to
def converter(file_name):
# do something
I've been extensively searching through Google and StackOverflow, but can't find anything that doesn't require the use of special characters like $ or command line options like -c. Does anyone know how to do this?
You can use something like PyInstaller to create a exe out of your py-file.
To use the argument in python:
import sys
if __name__ == "__main__":
converter(sys.argv[1])
You can type in the windows shell:
python converter.py file_name.txt
to give the arguments to the sys.argv list within python. So to access them:
import sys
sys.argv[0] # this will be converter.py
sys.argv[1] # this will be file_name.txt
at the bottom of the file you want to run, add:
if __name__ == "__main__":
converter(sys.argv[1])
To have a second argument:
python converter.py file_name1.txt file_name2.txt
This will be the result:
import sys
sys.argv[0] # this will be converter.py
sys.argv[1] # this will be file_name1.txt
sys.argv[2] # this will be file_name2.txt
I would recommend using something like the builtin argparse (for 2.7/3.2+) or argparse on pypi (for 2.3+) if you're doing many complicated command line options.
Only way I can think of is to create a batch file of the same name and within it, call your python script with the parameters provided.
With batch files you don't have to specify the extension (.bat) so it gets you closer to where you want to be.
Also, without any compiling .py to .exe, you may make your script 'executable', so that if you issue command line like myscript param param, the system will search for myscript.py and run it for you, as if it was an .exe or .bat file.
In order to achieve this, configure the machine where you plan to run your script:
Make sure you have file associations set (.py to python interpreter, that is, if you doubleclick at your script in the explorer -- it gets executed). Normally this gets configured by the Python installer.
Edit the COMSPEC environment variable (look inside My Computer properties) to include .PY extension as well as .EXE, .COM, etc.
Start a fresh cmd.exe from Start menu to use the new value of variable. Old instances of any programs will see only old value.
This setup could be handy if you run many scripts on the same machine, and not so handy if you spread you scripts to many machines. In the latter case you better use py2exe converter to bundle up your application into a self-sufficient package (which doesn't require even python to be installed).