Tag Archives: A new session could not be created

[Solved] appium Error: A new session could not be created

Error reported in appium:

selenium. common. exceptions. SessionNotCreatedException: Message: A new session could not be created. (Original error: Command failed: C:\\WINDOWS\\system32\\cmd.exe /s /c “D:\\tools\\Android\\android-sdk\\platform-tools\\adb.exe -s 127.0.0.1:62001 shell “ps ‘uiautomator'””

Execute the command in the error message in CMD:

The error message reported is: bad PID ‘uiautomator’

Solution:

1. Find ADB.JS file In the appium installation directory. directory:\appium\node_modules\appium\node_Modules\appium-ADB\lib
2. Open ADB.JS, find the following code:

ADB.prototype.shell = function (cmd, cb) {
  if (cmd.indexOf('"') === -1) {
    cmd = '"' + cmd + '"';
  }
  var execCmd = 'shell ' + cmd;
  this.exec(execCmd, cb);
};

3. Add the following code below the above code

//add
ADB.prototype.shell_grep = function (cmd, grep, cb){
    if (cmd.indexOf('"') == -1){
        cmd = '"' + cmd + '"';
    }
    var execCmd = 'shell' + cmd + '| grep ' + grep;
    this.exec(execCmd, cb);
};

4. Find the following code:

ADB.prototype.getPIDsByName = function (name, cb) {
  logger.debug("Getting all processes with '" + name + "'");
  this.shell("ps '" + name + "'", function (err, stdout) {
    if (err) return cb(err);
    stdout = stdout.trim();
    var procs = [];
    var outlines = stdout.split("\n");
    _.each(outlines, function (outline) {
      if (outline.indexOf(name) !== -1) {
        procs.push(outline);
      }
    });
    if (procs.length < 1) {
      logger.debug("No matching processes found");
      return cb(null, []);
    }
    var pids = [];
    _.each(procs, function (proc) {
      var match = /[^\t ]+[\t ]+([0-9]+)/.exec(proc);
      if (match) {
        pids.push(parseInt(match[1], 10));
      }
    });
    if (pids.length !== procs.length) {
      var msg = "Could not extract PIDs from ps output. PIDS: " +
                JSON.stringify(pids) + ", Procs: " + JSON.stringify(procs);
      return cb(new Error(msg));
    }
    cb(null, pids);
  });
};

4. Comment out the above code, start with/* and end with */comment

5. Replace with the following code

//replace
ADB.prototype.getPIDsByName = function (name, cb) {
  logger.debug("Getting all processes with '" + name + "'");
  this.shell_grep("ps", name, function (err, stdout) {
    if (err) {
      logger.debug("No matching processes found");
      return cb(null, []);
    }
    var pids = [];
    _.each(procs, function (proc) {
    var match = /[^\t ]+[\t ]+([0-9]+)/.exec(proc);
    if (match) {
    pids.push(parseInt(match[1], 10));
    }
    });
    if (pids.length !== procs.length) {
      var msg = "Could not extract PIDs from ps output. PIDS: " +
      JSON.stringify(pids) + ", Procs: " + JSON.stringify(procs);
      return cb(new Error(msg));
    }
    cb(null, pids);
  });
};

6. Restart appium