How do I used 2 quotes in os.system? PYTHON - python

I have a little bit of problem when I'm trying to use 2 quotes in os.system..
I'm gonna launch a program with python, the directory has multiple spaces, and to launch something that has multiple spaces in CMD you need to put double quotes around it obviously.
And here comes the thingy..
my code looks like this:
import os
os.system("C:/t est/hello")
and since I used os.system, it will obviously just send C:/t est/hello that to CMD..
Now what I need is to send "C:/t est/hello" to cmd with quotes but I need python to understand that I need 2 quotes aswell. Can someone please help me?

If you want to add quotes to your command, simply do so. Possibly the easiest way is to use single quotes for your string:
os.system('"C:/t est/hello"')
If you want to write a double quote inside a string delimited by double quotes you need to escape it. That would be done like this:
os.system("\"C:/t est/hello\"")
However, it's just a lot easier to use subprocess instead and let it handle quoting for you. For example:
subprocess.check_call(['ls', 'some directory with spaces in'])
Even the documentation for os.system() recommends using subprocess:
The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

Related

How to open a file in its default program with python

I want to open a file in python 3.5 in its default application, specifically 'screen.txt' in Notepad.
I have searched the internet, and found os.startfile(path) on most of the answers. I tried that with the file's path os.startfile(C:\[directories n stuff]\screen.txt) but it returned an error saying 'unexpected character after line continuation character'. I tried it without the file's path, just the file's name but it still didn't work.
What does this error mean? I have never seen it before.
Please provide a solution for opening a .txt file that works.
EDIT: I am on Windows 7 on a restricted (school) computer.
It's hard to be certain from your question as it stands, but I bet your problem is backslashes.
[EDITED to add:] Or actually maybe it's something simpler. Did you put quotes around your pathname at all? If not, that will certainly not work -- but once you do, you will find that then you need the rest of what I've written below.
In a Windows filesystem, the backslash \ is the standard way to separate directories.
In a Python string literal, the backslash \ is used for putting things into the string that would otherwise be difficult to enter. For instance, if you are writing a single-quoted string and you want a single quote in it, you can do this: 'don\'t'. Or if you want a newline character, you can do this: 'First line.\nSecond line.'
So if you take a Windows pathname and plug it into Python like this:
os.startfile('C:\foo\bar\baz')
then the string actually passed to os.startfile will not contain those backslashes; it will contain a form-feed character (from the \f) and two backspace characters (from the \bs), which is not what you want at all.
You can deal with this in three ways.
You can use forward slashes instead of backslashes. Although Windows prefers backslashes in its user interface, forward slashes work too, and they don't have special meaning in Python string literals.
You can "escape" the backslashes: two backslashes in a row mean an actual backslash. os.startfile('C:\\foo\\bar\\baz')
You can use a "raw string literal". Put an r before the opening single or double quotes. This will make backslashes not get interpreted specially. os.startfile(r'C:\foo\bar\baz')
The last is maybe the nicest, except for one annoying quirk: backslash-quote is still special in a raw string literal so that you can still say 'don\'t', which means you can't end a raw string literal with a backslash.
The recommended way to open a file with the default program is os.startfile. You can do something a bit more manual using os.system or subprocess though:
os.system(r'start ' + path_to_file')
or
subprocess.Popen('{start} {path}'.format(
start='start', path=path_to_file), shell=True)
Of course, this won't work cross-platform, but it might be enough for your use case.
For example I created file "test file.txt" on my drive D: so file path is 'D:/test file.txt'
Now I can open it with associated program with that script:
import os
os.startfile('d:/test file.txt')

Using Popen in Python to execute bat script with variable

I have a python script that is calling a bat script called testrunner.bat which in turns executes a TestSuite in SOAPUI. I actually have gotten the external call to work just fine with the following command:
Popen("testrunner.bat -s\"CCT000 - Deploy Software Release\" -R\"TestSuite Report\" -E\"Default environment\" -Ppath.packages.sq=Y:\\NIGHTLY C:\\CI\\HEDeployment\\CI-XXX-DeploySwRelease")
However, I need to be able to have the software "level" to be dynamic and need to pass the variable level into the command in place of "NIGHTLY" so I can specify if it's nightly software, or stable, etc. I have seen that I should break all the arguments up separately, but I am having a hard time.
subprocess.Popen() can take a list of arguments as well as a string. So, this should work for you:
release_type = "NIGHTLY"
Popen(['testrunner.bat',
'-s"CCT000 - Deploy Software Release"',
'-R"TestSuite Report"',
'-E"Default environment"',
'-Ppath.packages.sq=Y:' + release_type,
'C:CIHEDeploymentCI-XXX-DeploySwRelease'])
As mentioned in the docs, shlex.split can be very useful for splitting your original command string into pieces. However, at least in my case, I had to re-add the double quotes.
Also, recall that single-quoted strings can contain double quotes, and vice versa, so you don't need to escape the quotes here.

Python system argument reading '&'

I want to pass url to my python via the console and then do the appropriate tasks. many of the links contain the character '&' in the link. python interprets that as ending the argument this however is not what I want. here is a sample of the code
import sys
external_id = sys.argv[1].encode("utf-8")
print external_id
And when I run the following:
python graph.py 2%60&7
I get:
2%60
How do I make python interpret the '&' as nothing more than another character in the url?
This is not python, it's bash. You need to escape it:
python graph.py 2%60\&7
Quoting this answer:
The & informs the shell to put the command in the background.
Python never receives that character because the shell takes care of it, thus this isn't an issue of Python. You can also wrap 2%60&7 with quotes to make it work
me#pc:~$ python3 script.py '2%60&7'
b'2%60&7'
Sometimes escaping & is a lot harder than doing this.

Program error while using python subprocess.call() function

I'm trying to open a program while I'm in a python script using the subprocess.call() function, It opens the program but for some reason the program doesn't allows that and just throw an "Unhandaled exception" error, I know the problem is probably in the program so there may be any other command that will open a program, fill some fields and press "Submit?"
Thanks!
Edit: I've no code to post..
str = 'd:\Softwares\X.exe'
subprocess.call(str)
I've also tried with:
subprocess.call(str,shell=True)
Try calling another program the same way. If the problem persists, the problem is with your code. If it goes away, the problem is with the program.
I think changing to 'D:/Softwares/X.exe' or one of the other string formats will help because the '\' character is the escape character ... used for example to denote a new line '\n'.
It probably works if you use forward-slashes (backslashes are escape symbols in Python). If it doesn't, write the first line like this:
str = r'd:\Softwares\X.exe'
The r tells Python that you are creating a raw string, so it will ignore escape symbols. More information at: https://docs.python.org/2/reference/lexical_analysis.html#string-literals

Recreating a shell-like interpreter within python?

Before I sit down and start hacking it out, I thought I'd come here and see if you all had any tips or even if something like this has been done before.
I want to re-create a basic shell like syntax within a python program. In other words, when people run the file with python, they will be greeted with a little prompt
>>
For simple things, using an option parser to say
opt.parse_args(input.split(" "))
Works just fine, but now I would like to not only escape special characters like spaces with the '\' character, but also treat quoted strings as a single argument, like in a unix shell.
Does there exist anything that might already help with this?
Thanks for any suggestions!
- Chase
Start with the shlex module:
$ pydoc shlex
Help on module shlex:
NAME
shlex - A lexical analyzer class for simple shell-like syntaxes.
You can use it like this:
>> import shlex
>> shlex.split('This "is a" test.')
['This', 'is a', 'test']
This just splits things up into logical tokens; it won't do anything like variable expansion and so forth. That's still up to you, as is actually running commands.
Have you seen shlex from the standard library? Check out this example.

Categories