I am currently working on a python script in which there is a moment I want to delete a file which name is ending with .txt
To do so I just run a command line using os in python:
os.system("del working/*.txt")
When running the python script, I get the following error in cmd:
Option non valide - "*". which can be translated "Invalid option"
It seems that the wildcard isn't recognized by cmd but I know very little about this. Why is it not working ?
I know I could handle the situation with regular expressions but I'd like to understand.
Thank you in advance
In Windows, \ is the path delimiter, not /, so you should do:
os.system(r"del working\*.txt")
Note that / in Windows is for switches, hence the "invalid option" error.
I think its better use os.remove instead os.system with "del" command. Using os.system your script will not work on linux. Here a example using os.remove:
files = os.listdir("working\")
for fi in files:
if fi.endswith(".json"):
os.remove("working\{}".fomat(fi))
Related
I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.
The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?
To clarify from current responses:
I am using the subprocess module
I am passing the command line + arguments in as a list
The issue is with the path to the command itself, not any of the arguments
I've tried quoting the command. It causes a [Error 123] The filename, directory name, or volume label syntax is incorrect error
I'm using no shell argument (so shell=false)
In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin
It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.
The command that is failing is:
p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)
when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.
Make sure you are using lists and no shell expansion:
subprocess.Popen(['command', 'argument1', 'argument2'], shell=False)
Try quoting the argument that contains the &
wget "http://foo.com/?bar=baz&baz=bar"
Is usually what has to be done in a Linux shell
To answer my own question:
Quoting the actual command when passing the parameters as a list doesn't work correctly (command is first item of list) so to solve the issue I turned the list into a space separated string and passed that into subprocess instead.
Better solutions still welcomed.
"escaping the ampersand with ^"
Are you sure ^ is an escape character to Windows? Shouldn't you use \?
I try a situation as following:
exe = 'C:/Program Files (x86)/VideoLAN/VLC/VLC.exe'
url = 'http://translate.google.com/translate_tts?tl=en&q=hello+world'
subprocess.Popen([exe, url.replace("&","^&")],shell=True)
This does work.
I am trying to run the IBM Rational AppScan command line tool in python to iterate through .scan files in Windows and create xml reports. I am using python3.7.4 to do this and I am using the subprocess module. What I am trying continuously fails because of an unknown flag due to a single quote.
I am trying to run this python code on a Windows Server 2012. I have tried using os.system and subprocess.run with no luck.
Here is my code. It is looking for .scan files in the specified directory and when found attempts to run the command:
appscancmd r /b $scanfile /rtm Guidefault /rf $scanfile.xml /rt xml_report
Reference here for syntax:
https://www.ibm.com/support/knowledgecenter/en/SSPH29_9.0.3/com.ibm.help.common.infocenter.aps/r_ReportCommand004.html
import sys
import os
import subprocess
directory='C:\Scans'
for filename in os.listdir(directory):
if filename.endswith(".scan"):
scanfile=str(os.path.join(directory, filename))
command=['appscancmd', 'r /b "'+scanfile+ '" /rtm GuiDefault /rf "'+scanfile+'.xml" /rt xml_report']
subprocess.run(command)
continue
else:
continue
I keep receiving the error message:
Unknown flag entered: 'r /b "c:\scans\app.scan" /rtm guidefault /rf
"c:\scans\app.scan.xml" /rt xml_report'
and I believe this is due to the single quote inserted. When I manually run:
appscancmd r /b "c:\scans\app.scan" /rtm guidefault /rf "c:\scans\app.scan.xml" /rt xml_report
it works fine. Not sure how to resolve this, so figured I would ask for help
Jason, i figured out how to break each in the command list and was able to execute successfully. Thanks! command=['appscancmd', 'r', '/b', scanfile, '/rtm', 'GuiDefault', '/rf', scanfile+'.xml', '/rt', 'xml_report'] did the trick for those wondering
I've encountered some very strange behavior on Windows XP. I'm using Python to execute a command to open a browser using a shortcut file in a folder on the desktop.
The following line is what I expect to do the job:
os.system(r'"C:\Documents and Settings\you\Desktop\Chrome Browsers\Google Chrome 46.lnk" "chrome.google.com/webstore"')
It's a raw string literal so all the backslashes are actual backslashes. I can tell that is true by putting echo at the start of that command. (i.e. os.system('echo "C:\Documents and Settings\blah\blah chrome.google.com/webstore"') )
Using echo returns the following:
"C:\Documents and Settings\you\Desktop\Chrome Browsers\Google Chrome 46.lnk" "chrome.google.com/webstore"
That looks like a fine Windows command, yes? Well it is. Copying and pasting that into a command prompt runs fine. But the actual command (without echo) fails. The error states that
'C:\Documents' is not recognized as an internal or external command.
Which is a pretty standard error for an unquoted path. But wait, the command we echoed was good, so it should run, right? I guess not...
Through trial and error I was able to find something that worked. The following line is the only way I've been able to get the browser to launch:
os.system('""C:\Documents and Settings\you\Desktop\Chrome Browsers\Google Chrome 46.lnk" chrome.google.com/webstore"')
That's right, apparently the solution is to add an extra double quote at the beginning of the command and take out the double quote before the second argument.
To me that looks like empty string, unquoted path with unescaped spaces, then a quoted url that starts with a space.
If I echo that command it returns exactly what you would expect:
""C:\Documents and Settings\you\Desktop\Chrome Browsers\Google Chrome 46.lnk" chrome.google.com/webstore"
But it works! Pasting that echo result into the command line fails with the "C:\Documents not recognized" error from before, but the Python command opens the browser to the correct page anyway.
Could someone please explain what is happening here? I am really confused by this behavior because it is not at all what I expect.
P.S. This behavior is entirely different on every Windows OS past XP. For Vista and newer the command is:
os.system(r'"C:\Users\you\Desktop\Chrome Browsers\Google Chrome\Google Chrome 46.lnk" "chrome.google.com/webstore"')
Because there are " " spaces in your paths. C:\Documents and Settings\.. see the 2 spaces? otherwise it will pick up C:\Documents as a binary and and as the first param, Settings\.. as the other param.. and so on. This way youre saying: this whole thing is a binary C:\Documents and Settings\.. and chrome.google.com/webstore is my argument.
Make sense?
I know all about how Windows uses backslashes for filenames, etc., and Unix uses forward. However, I never use backslashes with strings I create in my code. However:
When windows explorer "drops" a file onto a python script, the string it passes contains backslashes. These translate into escape sequences in the strings in the sys.argv list and then I have no way to change them after that (open to suggestions there)
Is there any way I can somehow make windows pass a literal string or ... any other way I can solve this problem?
I'd love my script to be droppable, but the only thing preventing me is windows backslashes.
EDIT:
Sorry everyone, the error was actually not the passing of the string - as someone has pointed out below, but this could still help someone else:
Make sure you use absolute path names because when the Windows shell will NOT run the script in the current directory as you would from a command line. This causes permission denied errors when attempting to write to single-part path-names that aren't absolute.
Cannot reproduce. This:
import os, sys
print sys.argv
print map(os.path.exists, sys.argv)
raw_input()
gives me this:
['D:\\workspaces\\generic\\SO_Python\\9266551.py', 'D:\\workspaces\\generic\\SO_Python\\9254991.py']
[True, True]
after dropping the second file onto the first one. Python 2.7.2 (on Windows). Can you try this code out?
I'm currently having a major issue with a python script. The script runs arbitrary commands through a handler to convert incorrect error reporting into correct error reporting.
The issue I'm having is getting the script to work correctly on windows with a command that contains ampersands in it's path. I've attempted quoting the command, escaping the ampersand with ^ and neither works. I'm now out of ideas. Any suggestions?
To clarify from current responses:
I am using the subprocess module
I am passing the command line + arguments in as a list
The issue is with the path to the command itself, not any of the arguments
I've tried quoting the command. It causes a [Error 123] The filename, directory name, or volume label syntax is incorrect error
I'm using no shell argument (so shell=false)
In case it matters, I'm grabbing a pipe to stderr for processing it, but ignoring stdout and stdin
It is only for use on Windows currently, and works as expected in all other cases that I've tested so far.
The command that is failing is:
p = subprocess.Popen(prog, stderr = subprocess.PIPE, bufsize=-1)
when the first element of the list 'prog' contains any ampersands. Quoting this first string does not work.
Make sure you are using lists and no shell expansion:
subprocess.Popen(['command', 'argument1', 'argument2'], shell=False)
Try quoting the argument that contains the &
wget "http://foo.com/?bar=baz&baz=bar"
Is usually what has to be done in a Linux shell
To answer my own question:
Quoting the actual command when passing the parameters as a list doesn't work correctly (command is first item of list) so to solve the issue I turned the list into a space separated string and passed that into subprocess instead.
Better solutions still welcomed.
"escaping the ampersand with ^"
Are you sure ^ is an escape character to Windows? Shouldn't you use \?
I try a situation as following:
exe = 'C:/Program Files (x86)/VideoLAN/VLC/VLC.exe'
url = 'http://translate.google.com/translate_tts?tl=en&q=hello+world'
subprocess.Popen([exe, url.replace("&","^&")],shell=True)
This does work.