Question: Essentially, I want to create a script with multiple choices to check certain data on a hostname. For example, the code here will have an option to ping or run a `tracert` on a given hostname.

```
import os

print("""What did you want to run? (pick a number)
        (1) Ping
        (2) Traceroute""")

runit = raw_input("> ")

print ("Enter a hostname to check")
host = raw_input("> ") #accept input for hostname

if runit == "1":
    os.system("cmd /c ping " + host) 
elif runit == "2":
    os.system("cmd /c tracert " + host)

```

The code above works and I can get the results and manually copy them, but I would like this to be done automatically. I know I can open files using something like 

```
p = open("ping1.txt", "w")

```

But I am not sure how to copy the results of the trace or the ping from the command prompt? Any help would be appreciated.

Answer: 
[`os.system(command)`](https://docs.python.org/2/library/os.html#os.system) executes the command in a subshell and returns its exit status on most system (at least for cmd.exe).

The [subprocess](https://docs.python.org/2/library/subprocess.html#module-subprocess) module is much for suitable for doing anything more than that.

You probably want to use [subprocess.check\_output](https://docs.python.org/2/library/subprocess.html#subprocess.check_output) which runs the command with arguments and return its output as a byte string.

```
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)`

```
To redirect the output of a command to a file, you could pass `stdout` parameter to [`subprocess.check_call()`](https://docs.python.org/2/library/subprocess.html#subprocess.check_call):

```
#!/usr/bin/env python2
import subprocess

one_or_two = raw_input("""What did you want to run? (pick a number)
        (1) Ping
        (2) Traceroute
> """)
command = ["", "ping", "tracert"][int(one_or_two)]
host = raw_input("Enter a hostname to check\n> ") 

with open('output.txt', 'wb', 0) as file:
    subprocess.check_call([command, host], stdout=file)

```

If you want to display the output in the console in addition to copying the output to a file, see [Displaying subprocess output to stdout and redirecting it](https://stackoverflow.com/q/25750468/4279).