简体   繁体   中英

Calling a command line utility from Python

I am currently trying to utilize strace to automatically trace a programm 's system calls. To then parse and process the data obtained, I want to use a Python script.

I now wonder, how would I go about calling strace from Python? Strace is usually called via command line and I don't know of any C library compiled from strace which I could utilize.

What is the general way to simulate an access via command line via Python? alternatively: are there any tools similar to strace written natively in Python?

I'm thankful for any kind of help.

Nothing, as I'm clueless

You need to use the subprocess module.

It has check_output to read the output and put it in a variable, and check_call to just check the exit code.

If you want to run a shell script you can write it all in a string and set shell=True , otherwise just put the parameters as strings in a list.

import subprocess
# Single process
subprocess.check_output(['fortune', '-m', 'ciao'])
# Run it in a shell
subprocess.check_output('fortune | grep a', shell=True)

Remember that if you run stuff in a shell, if you don't escape properly and allow user data to go in your string, it's easy to make security holes. It is better to not use shell=True .

You can use commands as the following:

import commands
cmd = "strace command"
result = commands.getstatusoutput(cmd)
if result[0] == 0:
   print result[1]
else:
   print "Something went wrong executing your command"

result[0] contains the return code, and result[1] contains the output.

Python 2 and Python 3 (prior 3.5)

Simply execute:

subprocess.call(["strace", "command"])

Execute and return the output for processing:

output = subprocess.check_output(["strace", "command"])

Reference: https://docs.python.org/2/library/subprocess.html

Python 3.5+

output = subprocess.run(["strace", "command"], caputure_output=True)

Reference: https://docs.python.org/3.7/library/subprocess.html#subprocess.run

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM