Elinoter99
Elinoter99

Reputation: 619

Python passing parameters with os.system on linux

I've developed a python script on a Windows machine where at a point it calls another python script with some aruguments aswell.

script.py

value="bar"
id="foo"
os.system('"Main.py" %s %s' % (eqid, value))

main.py

 name=sys.argv[1]
 send=sys.argv[2]

This code works perfectly on Windows, and now im trying to run it on a Linux (Ubuntu) and im getting an error
sh 1: Main.py: not found
script.py and main.py are in the same directory asswell
What is wrong here? :/

Upvotes: 1

Views: 2523

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140307

linux probably doesn't have current dir in it's default path (security issue in case someone codes a malicious ls which is executed when you try to know what's in the directory).

So if the .py has the proper shebang you can do:

os.system('"./Main.py" %s %s' % (eqid, value))

but:

  • consider importing the script instead of running a subprocess (which is debatable, for instance if you want to preserve both processes independence)
  • os.system is now deprecated. A better approach would be using subprocess module.

Like this:

subprocess.call(["./Main.py",str(eqid), str(value)])

(note that to be stricly equivalent, I "converted" the arguments to strings, just in case they are, for instance, integers. That doesn't hurt)

Upvotes: 1

Jonathon McMurray
Jonathon McMurray

Reputation: 2991

You need to tell Linux how to run Main.py i.e. specify 'python "Main.py"' (this isn't needed on Windows if python is set as the default program to use to open .py files, but it should still work fine to specify it on Windows regardless)

e.g.

~ $ cat Main.py
import sys
name=sys.argv[1]
send=sys.argv[2]
print name+" "+send
~ $ python
Python 2.7.12 (default, Nov 20 2017, 18:23:56)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> value="bar";id="foo"
>>> os.system('python "Main.py" %s %s' % (id, value))
foo bar
0

But most likely you shouldn't be running a second python script like this, but should instead be importing it and calling it's code directly.

Upvotes: 2

Related Questions