tf.app.run()与argparse结合使用的疑问及argv参数作用解析
tf.app.run()'s argv Parameter with argparse Let's break down what's happening here step by step, since you already get the basics of argparse:
1. First, what does parser.parse_known_args() do?
When you call this method, it parses all the command-line arguments you explicitly defined with parser.add_argument() (like --ps_hosts, --job_name, etc.) into the FLAGS object. The second return value, unparsed, is a list of all command-line arguments your argparse setup doesn't recognize—think of these as "leftover" args that aren't part of your custom configuration.
2. What's the point of tf.app.run() here?
tf.app.run() is TensorFlow's convenience wrapper for launching your main function. By default, it takes the full list of command-line args (sys.argv) and passes them along. But in your code, you're overriding this with a custom argv value—here's why:
3. Breaking down argv=[sys.argv[0]] + unparsed
Let's split this into parts:
sys.argv[0]: This is always the name/path of your script (e.g., if you runpython mnist_distributed.py, this value is"mnist_distributed.py"). Every command-line argument list starts with this, so we need to keep it to maintain proper program context.unparsed: These are the args yourargparseparser didn't handle. By adding them toargv, you're passing them off to TensorFlow's internal argument handling system. For example, TensorFlow has its own built-in command-line flags (like--logtostderror--vfor verbosity) that aren't defined in your custom parser—this lets those flags still work as expected.
4. Why does main() use def main(_)?
By default, tf.app.run() will pass the argv list (minus the first element, the script name) to your main function. But since you've already handled all the args you care about via argparse, you don't need these extra args. The underscore _ is just a standard Python placeholder for a parameter you don't intend to use—it tells readers "I know this parameter is here, but I'm not going to use it."
Example to make it concrete
Suppose you run your script like this:
python your_script.py --ps_hosts=localhost:2222 --worker_hosts=localhost:2223 --job_name=worker --task_index=0 --tf_log_level=1
- Your
argparseparser recognizes--ps_hosts,--worker_hosts,--job_name,--task_index—these go intoFLAGS. --tf_log_level=1is not defined in your parser, so it ends up inunparsed.- The
argvpassed totf.app.run()becomes["your_script.py", "--tf_log_level=1"]. - TensorFlow's internal code picks up
--tf_log_level=1and adjusts logging accordingly, while yourmain(_)function ignores the unused parameter.
内容的提问来源于stack exchange,提问作者Huzo

