I’ve been running some python code on Windows which opens up another python program ‘main_plot.py’ using the following line…
subprocess.Popen(['C:\\python26\\python.exe ','main_plot.py','-n', str(number_of_cores),'-m', str(number_of_motors)])
I’ve tried to ssh into a Mac OS pc to run the same code but it doesn’t work because I think I need to change the path. This was my first guess…
subprocess.Popen(['python','main_plot.py','-n', str(number_of_cores),'-m', str(number_of_motors)])
but I get the error…
python: can’t open file ‘main_plot.py’: [Errno 2] No such file or directory
I’ve also tried
subprocess.Popen(['python','~/code/stochastic/main_plot.py','-n', str(number_of_cores),'-m', str(number_of_motors)])
but I get the same error.
I’ve checked that the file is in ‘~/code/stochastic’ and it is. I’m a bit stuck as what to do next
The problem isn’t a difference between Windows and Mac; it’s that you’re only using
~on Mac, and you can’t use~in a pathname.Put a different way,
~/code/stochastic/main_plot.pyis not a real pathname—or, rather, it is, but it’s looking for a directory named~under the current directory, not your home directory. The shell turns that into the real pathname using tilde-expansion. Python can do tilde-expansion as well, but you have to ask it to do so explicitly.So, the solution is simple:
As Jeremy Roman points out in a comment, you can use
~in paths if you useshell=True, because then Python will put all of your args together into a command line to pass to the shell, and the shell does handle~. But you don’t want to do that. Just callexpanduser.For future reference, the same thing is true for all the other kinds of expansion the shell does. You can’t do
"${HOME}/foo", but you can doos.path.expandvars("${HOME}/foo"). You can’t do"foo$((1+1))bar"; you have to do something like"foo%sbar" % (1+1,). And so on.