简体   繁体   中英

Problem while running python script in java code

When i run a python script from the below java code, where an input file is given as an argument to the python script as well as an "-v" option, i get a IOException

String pythonScriptPath="\"C:\\Program Files\\bin\\CsvFile.py\"";
String Filepath="C:\\Documents and Settings\\user\\Desktop\\arbit.csv";
String[] cmd = new String[4];
cmd[0] = "python";
cmd[1] = pythonScriptPath;
cmd[2] = "-v";
cmd[3] = Filepath;
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(cmd);

The following is the error:

CreateProcess: python "C:\Program Files\bin\CsvFile.py" -v "C:\Documents and Settings\user \Desktop\arbit.csv" error=2
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)

Can somebody please let me know how to solve this exception.

Thanking You, Harsha

error=2 means the Win32 CreateProcess function is returning an error code of 2, or ERROR_FILE_NOT_FOUND . Either it can't find your script, or (more likely, IMO) it can't find python.exe . If it's the latter, make sure your Python installation (possibly C:\\Program Files\\Python\\bin , though I'm not sure) is in your system path.

You can change your system path by going into the Control Panel and opening up "System". If you're using Vista or 7, click "Advanced system settings"; if you're using XP or 2000, choose the "Advanced" tab. Hit "Environment Variables", find "Path" or "PATH" under "System variables" and add your Python bin directory to the beginning of the string (it's semicolon-delimited).

You don't need all the extra quotes.

String pythonScriptPath="C:\\Program Files\\bin\\CsvFile.py";

This should work fine.

  1. Is Python in your path ? I would most likely qualify it with a path to determine precisely which python you're picking up (if any)
  2. You don't need the quotes around the Python script argument

Your variable Filepath does not match what you actually sent it according to your program output. The error lists it as "C:\\Documents and Settings\\user \\Desktop\\arbit.csv" with an extraneous space after the user profile name which is the most likely cause for a File Not Found error.

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