Search code examples
pythonbashcommand-lineipythonspyder

Distinguish runs from Command Prompt vs Spyder console


I am working on a script that needs to be run both from a command prompt, such as BASH, and from the Console in Spyder. Running from a command prompt allows the script file name to be followed by several arguments which can then be utilized within the script; >python script1.py dataFile.csv Results outputFile.csv. These arguments are referenced within the script as elements of the list sys.argv.

I've tried using subprocess.run("python script1.py dataFile.csv Results outputFile.csv") to enable the console to behave as the command line, but sometimes it works fine and other times it needs certain arguments, like -f between python and the file name, before it will display what is displayed in the command line. Different computers disagree on whether such arguments help or hurt.

I've searched and searched, and found some clever ways to use technicalities of the specific operating system to distinguish, but is there something native to Python I can use?


Solution

  • If you import sys in the console and then call sys.argv, it will show you the value ['']. While running a script within Spyder expands that array to ['script1.py'] (plus the file address), it will still not get larger than one entry.

    If, on the other hand, you run the script from the command line the way you showed above, then sys.argv will have a value of ['script1.py', 'dataFile.csv', 'Results', 'outputFile.csv']. You can utilize the differences between these to distinguish between the cases.

    What are the best differences to use? You want to distinguish between two possibilities, so an if - else pair would be best in the code. What's true in one case and false in the other? if sys.argv will not work, because in both cases the list contains at least one string, so that will be effectively True in both cases.

    if len(sys.argv) > 1 works, and it adds the capability to run from the command line and go with what is coded for the console case.