1

Suppose I have a python file main.py, and it has some optional parameters, --learning-rate, --batch-size, and etc.

If I want to run this file, I can input the following into the terminal(Ubuntu Linux for example).

python3 main.py --learning-rate 0.1 --batch-size 100

And now, I want to write some code in main.py, in order that after I enter the command above, I can get this command in a string by executing those code. The following is the string I want to get:

"python3 main.py --learning-rate 0.1 --batch-size 100"

The reason I want to do this is that I want to write this string into my recording file so that I can know better what command I have run.

Could anyone tell me what package should I import and what code should I write to get that command information during running the python file?

Thanks!

Leo
  • 73
  • 5
  • Possible duplicate of [How to read/process command line arguments?](https://stackoverflow.com/questions/1009860/how-to-read-process-command-line-arguments) – Will Aug 24 '18 at 17:59
  • 1
    `sys.argv` contains the arguments; the exact string that produces those arguments isn't readily available to Python, as the shell may have processed it first. – chepner Aug 24 '18 at 17:59

2 Answers2

0

Why not just remake the command using the arguments you parsed? It won't be exactly what you typed, but that might be nice as it will be in a common format.

Ex (assuming the learning rate and batch size are stored in similarly named variables):

command = "python3 main.py --learning-rate {} --batch-size {}".format(learning_rate, batch_size) 

Of course it will be a little more complicated if some commands are optional, but I assume in that case there would be a default value for these parameters, since your network would need those parameters every time.

TheMagicalCake
  • 309
  • 1
  • 6
  • 13
  • Thank you! I guess in some cases I have some optional parameters, so use `sys` can be more helpful – Leo Aug 25 '18 at 03:46
0

You cannot always get precisely what you typed, because the shell will have first done substitutions and expanded filenames before starting your script. For example, if you type python "foo.py" *.txt, your script won't see *.txt, it will see the list of files, and it won't see the quotes around foo.py.

With that caveat out of the way, the sys module has a variable named argv that contains all of the arguments. argv[0] is the name of the script.

To get the name of the python executable you can use sys.executable.

To tie it all together, you can do something like this:

print(sys.executable + " " + " ".join(sys.argv))
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685