How to Read/Process Command Line Arguments

How to read/process command line arguments?

The canonical solution in the standard library is argparse (docs):

Here is an example:

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")

args = parser.parse_args()

argparse supports (among other things):

  • Multiple options in any order.
  • Short and long options.
  • Default values.
  • Generation of a usage help message.

How to get the command line args passed to a running process on unix/linux systems?

There are several options:

ps -fp <pid>
cat /proc/<pid>/cmdline | sed -e "s/\x00/ /g"; echo

There is more info in /proc/<pid> on Linux, just have a look.

On other Unixes things might be different. The ps command will work everywhere, the /proc stuff is OS specific. For example on AIX there is no cmdline in /proc.

How to read command line arguments of another process in C#?

If you did not use the Start method to start a process, the StartInfo property does not reflect the parameters used to start the process. For example, if you use GetProcesses to get an array of processes running on the computer, the StartInfo property of each Process does not contain the original file name or arguments used to start the process. (source: MSDN)

Stuart's WMI suggestion is a good one:

string wmiQuery = string.Format("select CommandLine from Win32_Process where Name='{0}'", processName);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection retObjectCollection = searcher.Get();
foreach (ManagementObject retObject in retObjectCollection)
Console.WriteLine("[{0}]", retObject["CommandLine"]);

How to check if a process with Command line argument is running using python

To search through the currently running processes, you should use a library such as psutil to ensure maximum platform compatiblity.

import psutil

for process in psutil.process_iter():
cmdline = process.cmdline
if "main.py" in cmdline and "testarg" in cmdline:
# do something

If instead you are looking to search through the arguments of the current process you can use the sys.argv list:

import sys

if "testarg" in sys.argv:
# do something

For more complex argument parsing, it is recommended to use argparse.

Can I get command line arguments of other processes from .NET/C#?

This is using all managed objects, but it does dip down into the WMI realm:

private static void Main()
{
foreach (var process in Process.GetProcesses())
{
try
{
Console.WriteLine(process.GetCommandLine());
}
catch (Win32Exception ex) when ((uint)ex.ErrorCode == 0x80004005)
{
// Intentionally empty - no security access to the process.
}
catch (InvalidOperationException)
{
// Intentionally empty - the process exited before getting details.
}

}
}

private static string GetCommandLine(this Process process)
{
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id))
using (ManagementObjectCollection objects = searcher.Get())
{
return objects.Cast<ManagementBaseObject>().SingleOrDefault()?["CommandLine"]?.ToString();
}

}

Get Process's Command Line and arguments from Process object?

Well you could use WMI, there is a class that could be queryied to retrieve the process list and each object contains also a property for the command line that started the process

string query = "SELECT Name, CommandLine, ProcessId, Caption, ExecutablePath " + 
"FROM Win32_Process";
string wmiScope = @"\\your_computer_name\root\cimv2";
ManagementObjectSearcher searcher = new ManagementObjectSearcher (wmiScope, query);
foreach (ManagementObject mo in searcher.Get ())
{
Console.WriteLine("Caption={0} CommandLine={1}",
mo["Caption"], mo["CommandLine"]);
}

How to get command line args of a process by id?

you can use wmi to get this kind of info

var q = string.Format("select CommandLine from Win32_Process where ProcessId='{0}'", processId);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(q);
ManagementObjectCollection result = searcher.Get();
foreach (ManagementObject obj in result)
Console.WriteLine("[{0}]", obj["CommandLine"]);

Reading Command Line Arguments of Another Process (Win32 C code)

To answer my own question, I finally found a CodeProject solution that does exactly what I'm looking for:

http://www.codeproject.com/KB/threads/GetNtProcessInfo.aspx

As @Reuben already pointed out, you can use NtQueryProcessInformation to retrieve this information. Unfortuantely it's not a recommended approach, but given the only other solution seems to be to incur the overhead of a WMI query, I think we'll take this approach for now.

Note that this seems to not work if using code compiled from 32bit Windows on a 64bit Windows OS, but since our modules are compiled from source on the target that should be OK for our purposes. I'd rather use this existing code and should it break in Windows 7 or a later date, we can look again at using WMI. Thanks for the responses!

UPDATE: A more concise and C only (as opposed to C++) version of the same technique is illustrated here:

http://wj32.wordpress.com/2009/01/24/howto-get-the-command-line-of-processes/

Get command line from calling process

Combining the link from Wapac's comment with the Simon Mourier's answer in this question solved the problem.

Now I have two helper classes:

  1. CommandLineUtilities
  2. ParentProcessUtilities

In my program I just need to call now:

Process process = Process.GetCurrentProcess();
Process parent = ParentProcessUtilities.GetParentProcess(process.Id);
String[] parameters = CommandLineUtilities.getCommandLinesParsed(parent);


Related Topics



Leave a reply



Submit