0

Suppose I need to run a python file, x.py, from within y.py, passing variable z from y.py to x.py.

How would I accomplish this? Would something like this work?

call(["python","x.py",z])
4
  • 1
    docs.python.org/3/library/subprocess.html#subprocess.call Commented Apr 15, 2013 at 17:42
  • 1
    Does x.py accept command line arguments? Commented Apr 15, 2013 at 17:43
  • 1
    You should encapsulate the functionality of y in a function, then import that function in to x and call it appropriately. Commented Apr 15, 2013 at 17:47
  • That will work if call is subprocess.call and z is a string. You need to write some code and do some experimenting. Commented Apr 15, 2013 at 18:02

3 Answers 3

1

You need to encapsulate your code correctly. You should have something like this:

y.py

def y_func(*args):
    # everything y does
if __name__ == "__main__":
    import sys
    y_func(*sys.argv)

x.py

from y import y_func
def x_func(*args):
    #do stuff
    y_result = y_func(*yargs)
    #finish x stuff
if __name__ == "__main__":
    import sys
    x_func(*sys.argv)
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

# y.py
import os
z='argument'
os.system('Python x.py '+z)

Comments

0

Using subprocess is better than os.system

import subprocess
subprocess.check_output(["ls", "-ltr"])

In your case let's say you have a.py:

import sys
print sys.argv[1:]

and in the prompt:

>>> import subprocess
>>> subprocess.check_output(["python", 'a.py', 'aaa bbb ccc'])
"['aaa bbb ccc']\n"
>>> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.