Python, trying to run a program from the command prompt
-
21-09-2019 - |
Question
I am trying to run a program from the command prompt in windows. I am having some issues. The code is below:
commandString = "'C:\Program Files\WebShot\webshotcmd.exe' //url '" + columns[3] + "' //out '"+columns[1]+"~"+columns[2]+".jpg'"
os.system(commandString)
time.sleep(10)
So with the single quotes I get "The filename, directory name, or volume label syntax is incorrect." If I replace the single quotes with \" then it says something to the effect of "'C:\Program' is not a valid executable."
I realize it is a syntax error, but I am not quite sure how to fix this....
column[3] contains a full url copy pasted from a web browser (so it should be url encoded). column[1] will only contain numbers and periods. column[2] contains some text, double quotes and colons are replaced. Mentioning just in case...
Thanks!
Solution
Use the subprocess module for calling system commands. Also ,try removing the single quotes and use double quotes.
OTHER TIPS
- Windows requires double quotes in this situation, and you used single quotes.
- Use the
subprocess
module rather thanos.system
, which is more robust and avoids calling the shell directly, making you not have to worry about confusing escaping issues. - Dont use
+
to put together long strings. Use string formatting (string %s" % (formatting,)
), which is more readable, efficient, and idiomatic. - In this case, don't form a long string as a shell command anyhow, make a list and pass it to
subprocess.call
. - As best as I can tell you are escaping your forward slash but not your backslashes, which is backwards. A string literal with
//
has both slashes in the string it makes. In any event, rather than either you should use theos.path
module which avoids any confusion from parsing escapes and often makes scripts more portable.