passing a variable to cmd
Chris Angelico
rosuav at gmail.com
Sun Nov 6 08:59:57 EST 2016
More information about the Python-list mailing list
Sun Nov 6 08:59:57 EST 2016
- Previous message (by thread): passing a variable to cmd
- Next message (by thread): ANN: released psutil 5.0.0, introducing a 2x speedup for process methods
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Sun, Nov 6, 2016 at 10:48 PM, SS <sami.strat at gmail.com> wrote: > # cmd='dig @4.2.2.2 nbc.com ns +short' > cmd="dig @4.2.2.2 %s ns +short", % (domname) > proc=subprocess.Popen(shlex.split(cmd),stdout=subprocess.PIPE) > out,err=proc.communicate() > print(out) > > The line that is commented out works fine. However, I want to substitute a variable for "nbc.com". The command: Then don't use a single string; use a list of strings: cmd = ["dig", "@4.2.2.2", domname, "ns", "+short"] This is what shlex.split does, and you're fighting against things to try to force everything through that one channel. What happens if someone puts a space in domname? It should come back with an error from dig (you can't have spaces in domain names!), but with naive string interpolation, you would be passing multiple separate arguments. Get used to using lists of arguments for all command execution. Python isn't optimized for keyboard shorthands in running subcommands, the way an interactive shell is; it's designed more to be reliable and dependable. I wouldn't accept a shell that forced me to type commands with all their parts quoted, but I also don't use single strings with Python very often. This is the safer way. ChrisA
- Previous message (by thread): passing a variable to cmd
- Next message (by thread): ANN: released psutil 5.0.0, introducing a 2x speedup for process methods
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list