cd directory doesn't exist? - python

So, I made a command called jel, which is executable as jel. It is run in Python, and when I run jel doctor, in jel.py it gives me a error(the main file). The code looks like this: Note that all necessary modules are already imported.
elif arg == 'doctor':
subprocess.call(['cd', 'js'])
ver = subprocess.call(['node', 'version.js'])
subprocess.call(['cd', '..'])
if not ver == version:
print 'jel doctor: \033[91found that version\033[0m ' + str(version) + ' \033[91mis not the current version\033[0m'
print 'jel doctor: \033[92mrun jel update\033[0m'
sys.exit()
The js file version.js is run on node, and looks like this: All necessary packages are installed
var latest = require('latest');
latest('jel', function(err, v) {
console.log(v);
// => "0.0.3"
if (err) {
console.log('An error occurred.');
}
});
It is giving me this error when the jel.py file uses subprocess to call cs js and node version.js:
Traceback (most recent call last):
File "/bin/jel", line 90, in <module>
subprocess.call(['cd', 'js'])
File "/usr/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
bjskistad:~/workspace (master) $ jel doctor
Traceback (most recent call last):
File "/bin/jel", line 90, in <module>
subprocess.call(['cd', 'js'])
File "/usr/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
I believe it is saying the directory doesn't exist, although it does. Do I need to call something else before?

There are at least three problems with your code snippet:
cd is a shell built-in, not an executable program. If you want to invoke cd, you'll need to invoke the shell.
The cd command only affects the shell in which it runs. It will have no effect upon the python program, or any subsequent subprocesses.
The return code from subprocess.call() is not the text that the program wrote to stdout. To get that text, try subprocess.check_output().
Try this:
#UNTESTED
elif arg == 'doctor':
ver = subprocess.check_output(['cd js && node version.js'], shell=True)
if not ver == version:

As already pointed out changing the directory is only reflected in the subprocess. You should use os.chdir to change your working directory but another alternative is to specify the cwd to subprocess which avoids any need to cd or os.chdir:
version = subprocess.check_output(['node', 'version.js'], cwd="js")
You should also use != in your if and you probably want to rstrip the newline:
if version != ver.rstrip():

Related

Python subprocess call throws error when writing file

I'd like to use SVOX/pico2wave to write a wav-file from Python code. When I execute this line from a terminal the file is written just fine:
/usr/bin/pico2wave -w=/tmp/tmp_say.wav "Hello world."
I've verified that pico2wave is located in /usr/bin.
This is my Python code:
from subprocess import call
call('/usr/bin/pico2wave -w=/tmp/tmp_say.wav "Hello world."')
... which throws this error:
Traceback (most recent call last):
File "app/app.py", line 63, in <module>
call('/usr/bin/pico2wave -w=/tmp/tmp_say.wav "Hello world."')
File "/usr/lib/python2.7/subprocess.py", line 168, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 390, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1024, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
From the documentation
Providing a sequence of arguments is generally preferred, as it allows
the module to take care of any required escaping and quoting of
arguments (e.g. to permit spaces in file names). If passing a single
string, either shell must be True (see below) or else the string must
simply name the program to be executed without specifying any
arguments.
So you might try with
call(['/usr/bin/pico2wave', '-w=/tmp/tmp_say.wav', '"Hello world."'])

subprocess error message:[Errno 2] in _execute_child raise child_exception

In my program I call the command:
command_two = 'sfit4Layer0.py -bv5 -fs'
subprocess.call(command_two.split(), shell=False)
I am using PyCharm and I get the error message:
Traceback (most recent call last):
File "part2test.py", line 5, in <module>
subprocess.call(command_two.split(), shell=False) #writes the summary file
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
When walking through my program, it never gets to the program I want it to sfit4Layer0.py, it is getting stuck in subprocess but I am not sure why. Changing the shell=True doesn't do anything helpful either - I don't get these error messages but it does not execute my code properly. Any suggestions would be helpful.
My bash profile:
PATH="~/bin:/usr/bin:${PATH}"
export PATH PYTHONPATH="/Users/nataliekille/Documents/sfit4/pbin/Layer0:/Users/nataliekille/Documents/sfit4/pbin/Layer1:/Users/nataliekille/Documents/sfit4/pbin/ModLib:/Users/nataliekille/Documents/sfit4/SpectralDB"
export PYTHONPATH
PATH=${PATH}:${PYTHONPATH}
export PATH
You've missed an important part of the subprocess documentation. "If passing a single string [at the command, rather than a list of strings], either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments."
So the kernel is compaining because there is not executable with the name 'sfit4Layer0.py -bv5 -fs'. Should work if you replace the string with (for example) 'sfit4Layer0.py -bv5 -fs'.split(), or ['sfit4Layer0.py', '-bv5', '-fs'].

Python Subprocess clarification

I am trying to execute a program with python using subprocess
The format our professor gave us was subprocess(path/executableProgram)
File: OS377.py
I am doing it as subprocess(['/home/Joseph/OS377.py']) but I am getting errors
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.2/subprocess.py", line 471, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python3.2/subprocess.py", line 745, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.2/subprocess.py", line 1361, in _execute_child
raise child_exception_type(errno_num, err_msg)
OSError: [Errno 8] Exec format error
I need to execute a file using this format but am unsure how to go about it
Code:
def RUN(file):
pid = os.fork() #pid is non-zero in the parent process and 0 in the child
if pid: #parent
os.waitpid(pid,0)
elif pid == 0: #child
print("path is : ")
child(file)
def child(file):
#path = os.path.abspath(file)
#print(path)
subprocess.call(os.path.abspath('OS377.py'))
subprocess.call(['python', os.path.abspath('OS377.py')].
The file you're calling, a python script, may not be marked as executable (chmod u+x file.py). Alternatively, you should probably be executing it with $ python file.py - which is calling the python interpreter and passing it the name of your script as the first argument. So you should put it as subprocess.call(['python', '/home/Joe/file.py'].
Btw, did you mean subprocess.call() instead of just subprocess()?

Understand Python error message and resolve

I am not a Python programmer, but the make script is using some Python. And here I got this error message, I can see a stack trace. But how to track the problem from here?
/usr/bin/python2.7 ./config/pythonpath.py -I./config ./config/expandlibs_exec.py --depend .deps/libjs_static.a.pp --target libjs_static.a --extract -- /usr/local/bin/ar cr libjs_static.a bignum-dtoa.o bignum.o cached-powers.o diy-fp.o double-conversion.o fast-dtoa.o fixed-dtoa.o strtod.o jsalloc.o jsanalyze.o jsapi.o jsarray.o jsatom.o jsbool.o jsclone.o jscntxt.o jscompartment.o jsdate.o jsdbgapi.o jsdhash.o jsdtoa.o jsexn.o jsfriendapi.o jsfun.o jsgc.o jscrashreport.o jsinfer.o jsinterp.o jsiter.o jslog2.o jsmath.o jsmemorymetrics.o jsnativestack.o jsnum.o jsobj.o json.o jsonparser.o jsopcode.o jsproxy.o jsprf.o jsprobes.o jspropertycache.o jspropertytree.o jsreflect.o jsscope.o jsscript.o jsstr.o jstypedarray.o jsutil.o jswatchpoint.o jsweakmap.o jsworkers.o jswrapper.o jsxml.o prmjtime.o sharkctl.o ArgumentsObject.o ScopeObject.o Debugger.o GlobalObject.o ObjectImpl.o Stack.o String.o BytecodeCompiler.o BytecodeEmitter.o FoldConstants.o NameFunctions.o ParallelArray.o ParseMaps.o ParseNode.o Parser.o SPSProfiler.o TokenStream.o TestingFunctions.o Profilers.o LifoAlloc.o Eval.o MapObject.o RegExpObject.o RegExpStatics.o RegExp.o Marking.o Memory.o Statistics.o StoreBuffer.o StringBuffer.o Unicode.o Xdr.o ExecutableAllocator.o PageBlock.o YarrInterpreter.o YarrPattern.o YarrSyntaxChecker.o YarrCanonicalizeUCS2.o ExecutableAllocatorPosix.o OSAllocatorPosix.o jsperf.o pm_stub.o HashFunctions.o SHA1.o
Traceback (most recent call last):
File "./config/pythonpath.py", line 56, in <module>
main(sys.argv[1:])
File "./config/pythonpath.py", line 48, in main
execfile(script, frozenglobals)
File "./config/expandlibs_exec.py", line 322, in <module>
main()
File "./config/expandlibs_exec.py", line 311, in main
ret = subprocess.call(args)
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
make[1]: *** [libjs_static.a] Error 1
make[1]: Leaving directory `/priv
The first step would be to look into the source code; Python prints the file name and line number: File "/usr/lib/python2.7/subprocess.py", line 1249
When you look there, you'll see some code. The next step would then be to find out where each variable is assigned (i.e. who sets child_exception) and then what is necessary to execute this code until you come to a place where the code works with something that you provided (this follows the assumption that the Python library is probably correct and you made a mistake).
In your specific case, the problem is most likely that args[0] contains a path that point to a file / executable which doesn't exist.
So check where ./config/expandlibs_exec.py, line 311 gets args from and what's inside args[0]

How do I run a command with string formatting?

I am using the subprocess module to run a command in python. But the problem is that I also want to include a string (for a file name) in the command.
An example of what I want to do:
from subprocess import call
command = "cd/DirectoryName"
call = [(command)]
In this specific example I want DirectoryName to be a variable determined by the user.
What I have tried to no avail:
Desktop=raw_input()
cmd="'cd %s'(Desktop/)"
call([cmd])
Here's the error I get when I try to run these commands in the python shell.
Chicken='Chicken'
command = 'say %s' % (Chicken)
print command
say Chicken
call([command])
Traceback (most recent call last):
File "/Applications/WingIDE.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "/Library/Frameworks/EPD64.framework/Versions/7.2/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/Library/Frameworks/EPD64.framework/Versions/7.2/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/Library/Frameworks/EPD64.framework/Versions/7.2/lib/python2.7/subprocess.py", line 1228, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Just tried this and it made the shell crash.
Chicken="Chicken"
print Chicken
Chicken
call[("say %s" % (Chicken)]
That's not how string interpolation works.
cmd='cd %s' % (Desktop,)
First off,
cmd="'cd %s'(Desktop/)"
Doesn't seem like it would "printf" the %s.
Maybe
cmd="'cd %s/'%(Desktop)"
But I still don't know if that will interpolate since it's inside a string can using the "call" function and a python command -- wouldn't that call it on the command line?

Categories